I am going through a challenge on Freecodecamp and solved this problem, however I am not sure of some of the logic and just want to clarify
Please see below code
function findElement(arr, func) {
let num = 0;
for (let i = 0; i < arr.length; i++) {
if (func(arr[i]) === true) {
return arr[i];
}
}
return undefined;
}
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0))
I have 2 main questions
The console only logs 2 in this instance. Why would my for loop not continue and also log 4
Also, I understand why it logs a even number but then once this happens why does the code not move on to the next line and log undefined?
I initially put in a else statement to say following the loop else {return undefined;} though this didn't work and the return statement has to be outside of the for loop which I dont quite understand?
Thanks for the help on this one :)