why can’t we return undefined from the if loop like we would normally do?
function findElement(arr, func) {
let num = 0;
for (let i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
} else {
return undefined;
}
}
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/87.0.664.75.
It is working exactly like a normal if else. The very first time your function encounters a return statement, the function execution stops and the value is returned.
So your code above always returns on the first iteration of the loop.
Your current code does not run in a loop. It will only ever check the first value in the array arr because it either returns num or it returns undefined. Returning is the very last thing a function does. The return statement tells it to stop running immediately, so no code is ever executed after a return statement. A function cannot return more than once.