Tell us what’s happening:
Hi,
I have been noticing (depending on the solution for the problem) in cases where the if statement is used inside loops, we return either true or false outside the loop block. In this solution, the ‘return true statement comes after the for-loop’ Kindly help me understand why it is the case i had to place the ‘return true’ statement after the loop. I often fall into the trap of placing such statements inside the loops for lack of understanding why.
What you are doing is checking for a condition inside the loop. If the condition evaluates to true, you stop executing the rest of the code in the function and return a value. If you execute the entire loop without the if condition evaluating to true, you exit the loop and then return another value.
For example in the function below, I will loop through the numArr parameter looking for even numbers. If I find an even number, I return true because my goal is to determine whether the array has an even number. If I complete the loop without finding an even number, I return false.
const hasEven = ( numArr ) => {
for(let i = 0; i < numArr.length; i++){
// If you find an even number return true
if( numArr[i] % 2 === 0) return true;
}
// The loop has been exited without finding an even number.
return false;
}
console.log(hasEven([3, 5, 2, 7])); // true