Why can’t we return undefined from the if loop like we would normally do?

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.

Challenge: Finders Keepers

Link to the challenge:

What do you mean by normally? This function will return undefined for the first element that does not match the function.

Perhaps you want to only return undefined if every element does not match the function?

You can return undefined in a loop.
Any time you return without a value you are returning undefined.

// This will stop running and return undefined after printing "hi" three times
for(let i=0; i<100; i++){
    if (i === 3){
        return;
    }
    console.log("hi");
}

the code I posted above doesn’t work for the given lesson. You have to place “return undefined” behind the for loop. I don’t understand why.

I mean… i understand why that works, but I dont understand why it’s not workng like in the normal if/else procedure.

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.

1 Like

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.

2 Likes

whoops :yum: thank you both :blush:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.