Subtle point of return in JavaScript
After the instruction return is executed,
the function will finish its work and no further
code will be executed. See the example:
function func(num) {
return num ** 2;
console.log('!'); // this code will never run
}
let res = func(3);
This does not mean that the function should have
one return. But only one of them will be
executed. In the next example, depending on the
value of the parameter, either the first or the
second return will be executed:
function func(num) {
if (num >= 0) {
return '+++';
} else {
return '---';
}
}
console.log(func( 3)); // shows '+++'
console.log(func(-3)); // shows '---'
What will be output to the console as a result of executing the following code:
function func(num) {
return num;
let res = num ** 2;
return res;
}
console.log( func(3) );
Explain why.
What will be output to the console as a result of executing the following code:
function func(num) {
if (num <= 0) {
return Math.abs(num);
} else {
return num ** 2;
}
}
console.log( func(10) );
console.log( func(-5) );
Explain why.
What will be output to the console as a result of executing the following code:
function func(num) {
if (num <= 0) {
return Math.abs(num);
}
return num ** 2;
}
console.log( func(10) );
console.log( func(-5) );
Explain why.