Look at the function below. What will testReturn() output when called?
function testReturn() { for (let i = 0; i < 5; i++) { if (i === 2) { return i; } } return -1; } console.log(testReturn());
Remember that return immediately exits the function.
The function loops from 0 to 4. When i is 2, it returns 2 immediately, so the loop and function stop.
What will the function findFirstEven return?
function findFirstEven(arr) { for (const num of arr) { if (num % 2 === 0) { return num; } } return null; } console.log(findFirstEven([1, 3, 5, 6, 8]));
The function returns the first even number it finds.
The loop checks each number. The first even number is 6, so it returns 6 immediately.
What will this function output when called?
function nestedReturn() { for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i + j === 3) { return i * j; } } } return -1; } console.log(nestedReturn());
Check when i + j === 3 happens first and what i * j is then.
The first time i + j === 3 is true is when i=1 and j=2. Then i * j = 2. Since j only goes up to 2, this is the first valid pair.
What will this code output?
function testForEach() { [1, 2, 3].forEach(num => { if (num === 2) { return num; } }); return 'done'; } console.log(testForEach());
Remember that return inside forEach only exits the callback, not the outer function.
The return inside forEach stops the callback for that iteration only. The outer function continues and returns 'done'.
Consider these two functions:
function a(arr) {
for (const x of arr) {
if (x > 0) return x;
}
return null;
}
function b(arr) {
arr.forEach(x => {
if (x > 0) return x;
});
return null;
}Why does a([1,2,3]) return 1 but b([1,2,3]) returns null?
Think about what return does inside a callback function vs a loop.
Return inside a for-of loop exits the whole function immediately. Return inside a forEach callback only exits that callback, not the outer function.