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:
javascriptfunction 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:
javascriptfunction func(num) {
if (num >= 0) {
return '+++';
} else {
return '---';
}
}
console.log(func( 3)); // shows '+++'
console.log(func(-3)); // shows '---'
Задание 1
What will be output to the console as a result of executing the following code:
javascriptfunction func(num) {
return num;
let res = num ** 2;
return res;
}
console.log( func(3) );
Explain why.
Задание 2
What will be output to the console as a result of executing the following code:
javascriptfunction func(num) {
if (num <= 0) {
return Math.abs(num);
} else {
return num ** 2;
}
}
console.log( func(10) );
console.log( func(-5) );
Explain why.
Задание 3
What will be output to the console as a result of executing the following code:
javascriptfunction func(num) {
if (num <= 0) {
return Math.abs(num);
}
return num ** 2;
}
console.log( func(10) );
console.log( func(-5) );
Explain why.