What is the difference between:
function bla1(x){console.log(x)}
and
function bla(x){return console.log(x)}
I
With return
you specify what the value of a function
is. You can use this value to do further operations or to store it into a variable and so on.
Since console.log
return
s undefined
, the examples in your question are equivalent, as a function
not reaching a return statement will return undefined
as well. But let me give you an example:
function sum(arr) {
var s = 0;
for (var index in arr) {
s += arr[index];
}
return s;
}
function prodsum(arr, scalar) {
return scalar * sum(arr);
}
console.log(prodsum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));
The result will be 165. If we remove the return
s, then both function
s will return
undefined
:
function sum(arr) {
var s = 0;
for (var index in arr) {
s += arr[index];
}
s;
}
function prodsum(arr, scalar) {
scalar * sum(arr);
}
console.log(prodsum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));
and the result will be undefined
as well. Basically, if you want the function
to have a conclusion or final value, then you have a return
in it.