This forum is now read-only. Please use our new forums! Go to forums
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
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 return
s 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.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
1 comments
Thank you.I appreciate it.