What is the difference between:
function bla1(x){console.log(x)}
and
function bla(x){return console.log(x)}
In which cases should I use return
?
also, when a value is returned from a function, what happens to it? is it stored somewhere?
A return statement, rather than output information, makes a specific value available for use in a program at the place where the function was called. For example, the function in the code that follows computes the length of a hypotenuse and return s it. Then, it is up to the programmer what to do with that value.
There are two times you'll want to return in a function: When you literally want to return a value. When you just want the function to stop running.
The return statement ends function execution and specifies a value to be returned to the function caller.
Yes, it will end the method once a value is returned.
What is the difference
The first function returns undefined
(as it does not return
anything explicitly), the second one returns whatever console.log
returns.
In which cases should I use return?
When the function is generating some value and you want to pass it back to the caller. Take Math.pow
for example. It takes two arguments, the base and the exponent and returns the base raised to the exponent.
When a value is returned from a function, what happens to it? is it stored somewhere?
If you want to store the return value, then you have to assign it to a variable
var value = someFunction();
This stores the return value of someFunction
in value
. If you call the function without assigning the return value, then the value is just silently dropped:
someFunction();
These are programming basics and are not only relevant to JavaScript. You should find a book which introduces these basics and in particular for JavaScript, I recommend to read the MDN JavaScript Guide. Maybe the Wikipedia article about Functions is helpful as well.
Return in a function is a way to pass back data from the function.
Example:
function test(){
var test = 1+1;
return test;
}
var feedback = test(); //feedback would now contain the value 2 if outputted.
We could also send a variable into the function and then return it back out.
Example 2:
function test(i){
i= i+1;
return i;
}
var feedback = test(1); //feedback would also output the value 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With