问题
I'm trying to learn JS from Codecademy. I'm doing this excercise.
Can someone please tell me why return
is used instead of console.log()
?
I don't fully understand how return
works.
回答1:
console.log is useful for debugging purposes, but actually can't accomplish anything as far as affecting the surrounding code or application.
return is a way of "returning" a value generated by a function to the place it was called from. Think of it as giving a value to that function.
example:
function retFive(){
return 5;
}
var x = 37 + retFive();
console.log(x); //prints out 42
hope that helps!
回答2:
A function in code is really no different from a math function. Think about it this way:
f(x) = x+1
Which would "return" something based on the input of x
.
So f(1) = 2
because f(1)
returns the value of 1+1
.
Putting that into Javascript:
function f(x){
return x+1;
}
allows us to do this:
var y = f(1);
Now the value of y
is 2.
Without a return, we wouldn't be able to assign the value to y
.
console.log()
really does nothing. It just logs something to the console to view or debug values.
回答3:
return
has pretty much the same behavior as it does in other languages.
From the return MDN
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.
What this basically means is that when you call a function foo()
that has a statement like return 1;
it will have the value of 1
so: var bar = foo(); // bar = 1
function foo() {
return 1;
}
var bar = foo(); // bar = 1
console.log()
can be confusing if you're running the program in the console, it prints the value to the console so if our function foo
from before was function foo() { console.log(1); }
our var bar = foo();
would actually set bar
to undefined
.
function foo() {
console.log(1);
}
var bar = foo(); // bar = undefined
console.log() MDN
回答4:
Return
Is used to return a value from a function.
function foo(){
return 1;
}
console.log(foo()); //1
Useful when you have a function that does an operation that needs to return a value, and saves up space so you don't have to use a variable. It's generally just a more professional way of coding.
回答5:
Without answering about that exercise specifically, the purpose of a return
statement is to pass information from one function call to another. This information can be anything - an object, a string, a number, and can have any purpose, whether that be to return information about whether the function was successful or not, or to do a calculation and return the answer so another function can use it.
Console.log()
simply prints out whatever you pass in as a parameter to the console, which can change depending on your context. It doesn't have anything to do with relaying information from one part of your program to another.
来源:https://stackoverflow.com/questions/44439410/why-is-return-used-instead-of-console-log