Suppose we have a function that returns the
sum of numbers from 1
to 5
:
function func() {
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
return sum;
}
let res = func();
console.log(res); // shows 15
Now let's put return
inside
the loop, like this:
function func() {
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
return sum;
}
}
let res = func();
console.log(res);
In this case, the loop will scroll only one
iteration and the function will automatically
exit (well, at the same time, the loop will
exit). And after one iteration of the loop,
the variable sum
will contain only
the number 1
, and not the entire
required amount.
What will be output to the console as a result of executing the following code:
function func(num) {
let sum = 0;
for (let i = 1; i <= num; i++) {
sum += i;
return sum;
}
}
console.log( func(5) );
Explain why. What did the author of this code want to do? Correct the author's mistake.