This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Dennis Andersson
about 11 years

Return keyword, i dont understand at all :s

Hey, i wont get a hold of what the return keyword means. Can someone please explain it to me like if i were a 7 year old cuz im real stuck here!:S

Answer 510ab8a3e8be4dbcae000c8d

170 votes

Permalink

i’ll try to explain it in a shorter way:

let us define a simple function for adding two numbers:

var sum = function(number1, number2) {
    console.log(number1 + number2);
};

result = sum(1,3);

-> value 4 will be printed but variable result won’t have any value assigned so you cannot later reuse it

however, if you write this:

var sum = function(number1, number2) {
    return (number1 + number2);    	
};

result = sum(1,3);

-> value will not be printed but stored in a variable result so you can later reuse it..

so the main difference lies in storing the value in a variable

points
Submitted by anceque
about 11 years

33 comments

Jacob Toone over 10 years

THANK YOU! I have been trying to figure this out for days! AH! Thanks a ton!

anceque over 10 years

anytime :-)

Rob Harris over 10 years

Thank you anceque was not getting this at all. I got there in the end : )

anceque over 10 years

Great to hear, Rob! :-) keep on learning

Sindhuja over 10 years

Muchos gracias! Your a good teacher!

andrewhep over 10 years

Thanks =D

jhou over 10 years

well,im very confused here,…..good said: return (number1 + number2);
}; and 1+2= 3……why did you write (1,3) and not only 3? and whats value 4 and where does it comes from?……..

jhou over 10 years

i mean (you said) not ( good said)

anceque over 10 years

@jhou: there is no mention about adding 1+2. My example above is dealing with adding up 2 numbers, 1 and 3 (the result will be 4). number1 and number2 are parameters of the function called sum. this function is called in the variable called result in this line ‘result=sum(1,3);’. You can read it as: variable result calls function sum with parameters 1 and 3. function sum then returns result which is 4.

coderoma about 10 years

anceque - great post but I’m still missing something. You said that when using console.log that the “variable result won’t have any value assigned so you cannot later reuse it.” Continuing, you noted in contrast that when using return the “value will not be printed but stored in a variable result so you can later reuse it.” At least, that is what I think you are saying.

In the codecademy lab workspace, I entered the code with console.log, added other code, then tried to call result again. It worked. The code in the middle was this:

var divideByThree = function (number) { var val = number / 3; console.log(val); }; divideByThree(24);

Could you elaborate and perhaps provide an example that shows the difference between the two approaches?

Rithvik Shetty about 10 years

you could simply use: // Parameter is a number, and we do math with that parameter var timesTwo = function(number) { return number * 2; };

// Call timesTwo here! var newNumber = timesTwo(135); console.log(newNumber);

anceque about 10 years

Hi Johnny, sorry for replying so late - i didn’t see your post.. To answer your question, run this code, you created, and compare the results (i added another code for you to see the difference):

var divideByThree = function (number) { var val = number / 3; console.log(val);

};

number = divideByThree(24);

console.log(number);

// vs

var divideByThreeOption2 = function (number) { var val = number / 3; return val;

};

number2 = divideByThreeOption2(24);

console.log(number2);

anceque about 10 years

sorry for the format but i cannot influence it :) anyway, put // vs onto independent line as it is a comment

Mari about 10 years

dies of fustration and confusion WHY IS NOTHING EASY?

Aura13 almost 10 years

Much confuse…if it’s console.log, does the value get stored as well or is it only displayed?

Leon{CODES} almost 10 years

….just… wow… @jhou

lejon almost 10 years

you might want to try this link it might help you understand a little bit more http://www.codecademy.com/forum_questions/51ddb97a9c4e9dc865002996

anceque almost 10 years

@Aura13: console.log is just what the name says: logging an information on a console..it does NOT store any value - it only displays it

Kelvin Ng almost 10 years

I still don’t get it :s I’m stuck too

Michael Stepp over 9 years

So if the code block of a function is just a console.log statement, then even if you later give a variable the value of the function’s output, there’s nothing there to be given, because it was only displayed to the console and not saved? So by using the return keyword, you’re telling the function “hold on to this - someone else might need it”?

anceque over 9 years

@Michael Stepp: basically yes.. if i understand correctly

EdmondHasanaj over 9 years

thnx for this explain . i got it

tproll over 9 years

Awesome, I wish the lesson talked about the “reuse”/storing aspect.

lboud27 over 9 years

when do you use var val and when do you use console.log? they seem like they do the same thing

lboud27 over 9 years

what do u mean value will not be printed? do u mean it won’t show up in the small black box? Why not?

justwhitelol over 9 years

i do understand but i don’t know how to make it.

daffyunicorn about 9 years

i still dont get it :( ill try reading again

EthanDebnath about 9 years

i really am not getting it………..

Rideedee about 9 years

i don’t get it,can you explain again

ykakomba about 9 years

Me either, can someone explain it in plain English, English is my second language.thank you

Rideedee about 9 years

me too

Pac44 about 9 years

thanks

Uncle Ben almost 9 years

Is this case: var hot = function(number) {number + 8} won’t JS just add whatever number is put in for the parameter and the number 8 giving “hot” a value? Why does the return keyword have to be used here?

Answer 510a9bc045b0a8f1ae000644

70 votes

Permalink

Every expression in JavaScript has a value. That value – if it is simple enough to be printed – is what you see printed on the console when you say

console.log(some_expression);

For instance, the expression 5 has the value 5 – this is totally obvious, but you asked specifically to explain as if you were seven, so here you go ;)

The expression 5+5 has the value 10, and the expression "hello "+"world" has the value "hello world". Now if fun is a defined function that takes a parameter, then

fun( /*some_expression*/ )

is itself an expression. So what’s its value? Well, it’s precisely what you put to the right of the return keyword when defining your function. In the simplest case, when you have no return keyword in there at all, the value is undefined:

var fun1 = function(x) { /* do nothing */ };
console.log( fun1('hello') );               // ==> undefined

That’s one of the functions that always return the same value, independent of the argument – doesn’t matter whether you call it as fun1('hello'), fun1(false), or fun1([1,2,3]), the value that comes out the other end is always the same.

Another example would be

var no_matter_what(x) { return true; }
console.log( no_matter_what(100) );          // ==> true

Of course these functions aren’t hugely useful, because if you know the value it’ll return in advance then you can just use the value alone.

The really interesting functions are the ones that do something with their argument and return different values for different input. For instance,

var square = function(n) {
  var result = n * n;
  return result;
}

So the value of square(1) will be 1, but the value of square(3) will be 9 – that’s because the square function returns a variable whose value was calculated from the input (aka the argument).

points
Submitted by Alex J
about 11 years

16 comments

CWFranz about 11 years

This was very helpful, thanks! :)

Alex J about 11 years

Found it helpful? Upvote it :)

(^_^) over 10 years

So basically, the return value is a way to “store” values for other use? Thanks, it was helpful!

Daniel P over 10 years

This IS helpful! I will vote for it.

Tyler Mccormack about 10 years

thanks man this helped alot

Paradoxone about 10 years

This is very helpful, thank you :)

Mari about 10 years

I UNDERSTAND!! Call timesTwo in the newNumber slot var newNumber = timesTwo (10)

BunnyLover245 almost 10 years

What in the world

daaaayum, that was thorough and well explained. Thank you. Lesson 7/13 was really confusing me. Especially when it says notice how the value we return from timeTwo() is automatically assigned into new number. You kinda sorta cleared this up. Anyhow, really helpful explanation, in that it doesn’t just show a bunch of code and loosely explain it in other code. You really took the time to explain why and how and give good examples.

Evan over 9 years

That cleared it up for me thank you

cardamomclouds over 9 years

thank you!

ngdanielk over 9 years

Thank you!

Thanks, I have been been coding in Code Academy Javascript for about a month now and passed this but didn’t completely understand.

EthanDebnath about 9 years

ummm………….quite puzzled…this is one of the most pointless things in JavaScript to me. No offence.

Bashir Smair almost 9 years

why we have to use return wile we can type it like this : var square = function(n) { var result = n * n; console.log(result) };

hanvyj over 8 years

EthanDebnath, I don’t understand how you think it’s pointless - it’s a fundamental part of programming. With an inability to return anything functions are just… a complex print method. When you’re writing something complex you need to be able to use things that functions do.

Answer 529fd2a4282ae3411a00030c

43 votes

Permalink

Here, this is the easiest way to put it:

var newNumber = timesTwo(9) ; console.log(newNumber) ; var timesTwo = function(number) { return number * 2 ; };

points
Submitted by Tanvi B
over 10 years

13 comments

Dharmik Sankhala about 10 years

thanks :)

Sherif M Kamel about 10 years

Thanks for that code, was going to make me crazy!

osa galeano about 10 years

t Thanks you..

Enio Hysa almost 10 years

I thought you put an actual # in function(number)

KellyKwan77 almost 10 years

Thanks for the help! ^^

Mauro Franco almost 10 years

hi there are times that I get so tired that I forget to think Thanks for the tip

jueng over 9 years

sometimes you can figure out the logic when you just have the answer and work backwards–Thanks

supersen over 9 years

thanks!

Joseph Figueroa over 9 years

OH MAN thank you so much for this…was about to develop an ulcer off of this!

HASHAMWOW about 9 years

nice and simple, lets us figure it out while giving us a clear solution. Thanks!

TheDragonSlayer12329 about 9 years

Thank u so much Tanvi B, I was stuck until I read this :)

MeMakeCode almost 9 years

This code ONLY works for this lesson. Copy and paste this code into the first lesson and you will get a reference error (as you should). I’m guessing this is because this particular lesson pre-defines “timesTwo”, so you are able to reference it. Change it to “timesThree” within this lesson and it no longer works.

Answer 51e52d318c1ccc0969002de4

9 votes

Permalink

Thanks anceque for the clear response. Here is an actual demonstration of anceque’s response:

If your script looks like this:

var sum = function(number1, number2) 

{
    return (number1 + number2);     
};

var SpecificSumA = sum(1,1);

Then, when you do this:

console.log(SpecificSumA+1);

You will get an actual calculation, and the console will log “3”, this being the sum of 1+1+1.

But, if your script looks like this:

var sum = function(number1, number2) 

{
    console.log(number1 + number2);
};

var SpecificSumA = sum(1,1);

Then, when you do this:

console.log(SpecificSumA+1);

the console will log “2 NaN”.

The reason: When you write console.log(SpecificSumA) it implements the sum function with the specific parameter of (1,1), which as part of the function ‘sum’ is equivalent to 2. But the 2 is not calculated and saved internally, rather it is logged onto the console, since that is what ‘sum’ demands, as can be seen here:

var sum = function(number1, number2) 

{
    console.log(number1 + number2);
};

So when you add to the console.log(SpecificSumA+1) the +1 it can’t add them together since SpecificSumA is not a calculation saved to the script, rather it was just a calling of console.log. Since SpecificSumA and +1 are incompatible, only the “2” of the original console.log within SpecificSumA is displayed and NaN is also displayed.

points
Submitted by bobbysmith
over 10 years

2 comments

tbgemini615 over 9 years

This is quite helpful but you dont need to add { and } before and after console.log(SpecificSumA+1)?

Example: var sum = function(number1, number2)

{ console.log(number1 + number2); };

var SpecificSumA = sum(1,1) // { before console.log and } after console.log { console.log(SpecificSumA+1); }

This is clear, my eyeballs are sweating, I do not understand why SpecificSumA+1 returns 3. And remember we’re 7, this all sounds a little too wordy for a 7 year old.

Answer 541ad93b52f863ba4900225c

6 votes

Permalink

//This so far is best var timesTwo = function(number) { return number * 2; };

// Call timesTwo here! var newNumber = timesTwo() console.log(newNumber);

points
Submitted by stanley-need-solver
over 9 years

1 comments

Sumanth Mvs over 9 years

i wnt the code

Answer 545c058e52f86369b60005a7

4 votes

Permalink

// Define quarter here. var quarter = function(number) { return number / 4
}

if (quarter(12) % 3 === 0 ) { console.log(“The statement is true”); } else { console.log(“The statement is false”); }

// define a variable named quarter that has a function of number return that value decided by 4. don’t forget to open and close your body with the squiggly brackets. input a value at the function of quarter that when divided by 3 it has no remaining numbers. for ex: 12/3 = 4 and not 4.1, 4.6 etc.. Lets say you did 20/3, you would then use the number that came closest to 20 but not past it. for example 3 * 6 = 18, so your module would be the remainder 20 - 18 = 2. instead having a 2 you want your answer to come off as a whole number.

points
Submitted by vanilla211
over 9 years

Answer 5535f93c937676c2fb00004a

4 votes

Permalink

Further breakdown of the function timesTwo:

 var timesTwo = function(number) {
    var newNumber =  number * 2 ;
    console.log(newNumber);
 };

When you declare a function, the code in the ( ) is your function input. Within the function (between the { }), your input acts as a variable that only exists within the function, and the value of this variable will be specified later on whenever you call the function. So for now, when we declare (create) our function, number is simply a placeholder for future inputs and doesn’t have a value at the moment. The point of declaring the function is to code how number will be manipulated (in this case multiplied by two) once we give number a value later on.

timesTwo(9) ;

Here we call the function. When we declared the function, number was just a placeholder. Now notice that instead of the timesTwo(number) that we saw when we declared the function, we now see timesTwo(9). This is know as calling a function, and what it does is it replaces every instance of number within the function with the value 9. When we input 9 into our function, it’s looking at what we did to number when we declared the function and doing it to 9 instead. This is our original function with number replaced by 9:

var timesTwo = function(9) { var newNumber = 9 * 2 ; console.log(newNumber); }; .

Coding timesTwo(9) is the same as “hard coding” the following:

var myNumber = 9 var newNumber = myNumber * 2 ; console.log(newNumber);

Hope this helps! Please let me know if any of this is unclear and I’ll do my best to rewrite it. Thanks again MissOgra!

points
Submitted by MeMakeCode
almost 9 years

Answer 52e0032a631fe9fef5003b1f

2 votes

Permalink

Return in this case just means that like you sent the function a bucket of sand, and it made a sand pie, and then it puts the sand pie back in in the bucket and sends the bucket back to you.

points
Submitted by ndamato
about 10 years

3 comments

Hah, thank you, now my eyeballs are crying. That is funny.

MaskAndHelm over 9 years

I like that perspective.

ajdomino over 8 years

Wow. That actually helped me so much.

Answer 5535f908e39efe600200000e

2 votes

Permalink

Thanks for asking for the correct code MissOgra, I should have included it in this

post!

var timesTwo = function(number) {
return number * 2 ;
};
var newNumber = timesTwo(9) ;
console.log(newNumber) ;

In this case the first two lines declare the function. What this does is it creates a bloc (a section, or a bunch) of code that can be called multiple times without having to “hard code” it every time you want to do the same thing. In this case, we create a function timesTwo so that we can multiply a number by two by simply coding timesTwo(any number).

Example:

I want to multiply 8 by two, 7 by two, and 23 by two and send the new values to the console without changing the value of the original variables. If I hard code this, I get:

var firstNumber = 8
var secondNumber = 7
var thirdNumber = 23

var newFirstNumber = firstNumber * 2
console.log(newFirstNumber)

var newSecondNumber = secondNumber * 2
console.log(newSecondNumber)

var newThirdNumber = thirdNumber * 2
console.log(newThirdNumber)

Now lets do the same thing with a function:

var timesTwo(number){
var newNumber = number*2
console.log(newNumber)
}

timesTwo(8)
timesTwo(7)
timesTwo(23)

This is a pretty sloppy example of coding, but I hope it gets the idea across that functions can save you a whole lot of time and can make your code look much cleaner. .

points
Submitted by MeMakeCode
almost 9 years

2 comments

Sam4code almost 9 years

Thanks, your explanation made alot of plain ol’ sense.

MeMakeCode almost 9 years

You got it, glad I could help!

Answer 549719ee9113cb6a0400581f

1 vote

Permalink

var newNumber = timesTwo(7) ; console.log(newNumber) ; var timesTwo = function(number) { return number * 2 ; };

This is the way I did it, I hope it’s usefull.

points
Submitted by 19Andrew Sayegh
over 9 years

2 comments

mgevan7 about 9 years

Thankyou I wish they gave us a few examples first would of made this a lot easier to understand.

Tentacly about 9 years

I agree! Thanks for the visualization.

Answer 552f3c6676b8fe6ec0000248

1 vote

Permalink

NOTE: SOME OF THE CODE ABOVE IS NOT CORRECT, EVEN THOUGH IT WORKS IN THIS LESSON

Just a heads up to people reading this help topic, some of the code posted above is not correct even though it works in this lesson. You cannot call a function before it is declared, as in the code below:

var newNumber = timesTwo(9) ;
console.log(newNumber) ;
var timesTwo = function(number) {
return number * 2 ;
};

This code ONLY works for this lesson. Copy and paste this code into the first lesson and you will get a reference error (as you should). I’m guessing this is because this particular lesson pre-defines “timesTwo”, so you are able to reference it. Change it to “timesThree” within this lesson and it no longer works.

I’m guessing this is a bug in the lesson, where the function “timesTwo” is already established, whether you code it in or not. I also tried the following code within this lesson:

var newNumber = timesTwo(9) ;
console.log(newNumber) ;

It returned “18” when it obviously should not have returned anything but an error.

points
Submitted by MeMakeCode
almost 9 years

4 comments

MissOgra almost 9 years

Then how should it look like?… Im quite confused here :/

MeMakeCode almost 9 years

Ah, thanks for the comment, I should have posted the correct code in the post above. Sorry about that, I’ll add it now

MeMakeCode almost 9 years

Well, I tried to update my post, but it doesn’t seem to be sticking :/

Not sure if there’s bugs in the QA forum or if I’m violating some basic rule I’m not aware of. I’ll try to add the extra info in a new post here

MeMakeCode almost 9 years

Also, why was this down voted? If you think I’ve made a mistake, it’s much more useful if you leave a comment rather than simply clicking a down arrow :/

Answer 556e8c969113cb31ca000156

1 vote

Permalink

var newNumber =timesTwo(32);
console.log(newNumber);
points
Submitted by Subat
almost 9 years

Answer 5614f49595e3789eef0002b5

1 vote

Permalink

var timesTwo = function(number) { return number * 2; };

timesTwo(12);

//Perhaps this will help you better understand. The lesson is a little confusing when first learning because they are showing it in 2 steps which can be a little overwhelming. My example won’t get you a pass in the lesson so don’t cut n’ paste it, but it will help illustrate it in the simplest terms.

//Basically return won’t print the answer to the console.log. Instead it remembers the outcome and stores it for later use.

//Later when we call on timesTwo… as shown above timesTwo(12); … it remembers the stored value (which is the return) and substitutes it. For this example the answer would be 24.

points
Submitted by Jay Coder
over 8 years

Answer 557e96b5937676c8c60002c2

0 votes

Permalink

I got this:

// Parameter is a number, and we do math with that parameter var timesTwo = function(number) { return number * 2; }

// Call timesTwo here! timesTwo(8); var newNumber = 16; console.log(newNumber);

It worked somehow and I don’t know why haha…

points
Submitted by Kevin Koedam
almost 9 years

Answer 555ecc2276b8fe6b8c000361

2 votes

Permalink

var timesTwo = function(number) { return number * 2; };

// Call timesTwo here! var newNumber = timesTwo(8) console.log(newNumber);

points
Submitted by Akbar Pardayev
almost 9 years