The fact that return
is located inside
the loop may not always be a mistake. In the
following example, a function is made that
determines how many first elements of an array
must be added so that the sum becomes greater
than or equal to 10
:
function func(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
// If the sum is greater than or equal to 10:
if (sum >= 10) {
return i + 1; // exits the loop and the function
}
}
}
let res = func([1, 2, 3, 4, 5]);
console.log(res);
And in the following example, a function is made
that calculates how many integers, starting from
1
, must be added so that the result is
greater than 100
:
function func() {
let sum = 0;
let i = 1;
while (true) { // an infinite loop
sum += i;
if (sum >= 100) {
return i; // the loop runs until it exits here
}
i++;
}
}
console.log( func() );
Write a function that takes a number as a parameter
and divides it by 2
as many times until the
result is less than 10
. Let the function
return the number of iterations it took to achieve
the result.