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

0 points
Submitted by Jie
over 8 years

javascript / function /return

Guys, I’m sorry to bother you guys here but I really don’t get the “return” mean, However,I check a lot of case online but it still bother me a lot.

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

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

case two: 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”); }

I wonder if anyone could help me to explain more ,and the Number case two why they use “ return number/4” not “console .log(number/4)”instead with?? All my code is correct when I do the course but I confused and want to make it clear. I will really appreciate your help.god bless you guys. : )

Answer 557f6059e0a3007ff900096c

0 votes

Permalink

The first thing to clear from our minds is that console.log() and return are somehow the same or interchangeable. They are not. Not even remotely.

.log() is a method of the console object. Unless we have the console open, console.log() commands are ignored, and may have other consequences if we leave the statements in our production code. Production code is finished code that faces the web.

return on the other hand is intrinsic in every function. It is a way for us to hand a value back to the call site (where the function is called) and then use it in that scope, rather than function scope.

// function expression

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

// call expression
timesTwo(8);

Nothing happens. Why? Because we haven’t assigned the return value (or logged it).

var newNumber = timesTwo(8); // now it is assigned
console.log(newNumber); // output: 16
console.log(timesTwo(newNumber)); // output: 32

We are able to pass a number to the function, which performs a calculation and returns a result. The calculation is done in local scope, but the result is handed back to call site scope, which in this case is global. I call this scope jumping, but there are better terms that will come up in your reading. I hope you will take some time to do a little reading on the side and get these ideas cemented in your mind.

points
Submitted by Roy
over 8 years

1 comments

Jie over 8 years

Thank you.I appreciate it.