Am i understanding this correctly?


#1

when using "return" all its doing is using the code in the returned code correct? so when i set newNumber = timesTwo (9), its taking the 9, applying it to the timesTwo variable where "number" is on line 2, then running the code from the "return" multiplying the 9 by 2 correct. I hope im making sense as I've only been learning javascript for a few days.


#2

Hello there, the return function is kind of tricky thing to get a grasp on at first.

The way I like to think of it instead of using console.log is that whenever you are returning something,
say I do:

function myFunction(x) {
    return x * 2;
};

when I call that function that returns the 9 * 2 I actually have to set a variable up to contain the item it is returning. That way I have a variable holding the information for me to print, do more work with, etc. So, I'm simply passing the data from the function into a new as variable. As shown here:

var x = myFunction(9);
console.log(x) // This shows up in the console as 18

Instead of using console.log which simply outputs anything you'd like. Say if I did

function myFunction(x) {
    console.log(x*2);
};

myFunction(9); // This shows up in the console as 18
// but there is nothing holding this information so the 18 is used once then
// is released from data not to be seen or heard from again.

I hope this was helpful and made sense. If you have any questions let me know.


#3

Thanks for the quick reply!! So in your example, when you use the return function, its like writing down x * 2 to use later, and when you need to use that, you fill in "x" with what ever variable is needed by declaring it and calling the myFunction function.

thanks again for the help.


#4

its like writing down x * 2 to use later

Yes that is a pretty good way to think of it. When your function has a return statement your function call will have the value you get returned from the function for example:

var square = function(x){
    return x*x;
}

then you can of course write it to a variable:

var a = square(3);

but you could as well use this value just like any other value:

var c = a+square(4);

where it would behave the same way as if you'd write:

var c = a + x*x where x is 4

Just that you don't have to care about PEMDAS as the calculation was done before the return.

On the other hand if you use console.log you see the result on the screen but there is no value returned e.g.

console.log(console.log("test"));

would give

test // inner console.log
undefined // no value for the console.log itself

#5

Awesome, thanks alot for the clarification. I think I have a good idea on it now. :blush: