The Place of the "return undefined"

Tell us what’s happening:
Hello everyone,
I did not understand the reason why ‘return undefined’ line does not work under the if block while the code is working outside of the for loop? It seems there is no difference logically, I would be glad if you explain. Thanks.

Your code so far

function findElement(arr, func) {
for (let num of arr) {
  if (func(num)) {
    return num
  return undefined;

findElement([1, 2, 3, 4], num => num % 2 === 0);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15.

Challenge: Finders Keepers

Link to the challenge:

Your function stops execution the very first time it encounters a return.

But the instructions are

If no element passes the test, return undefined.

If the return undefined; is inside of your loop, then you return undefined the very first time you encounter an element that does not meet the if statement condition. If this return undefined; is outside of the loop, then you only return undefined after you have checked every element in your array.

1 Like

Also, just as an FYI.

The default return value from a function is undefined so in this case, you do not have to explicitly return undefined. If the logic inside the loop never caused a return, the function will implicitly return undefined.