Quick Question Please

Why can’t I include an else statement without conditions to the finders keepers challenge.

Why wouldn’t this work:

function findElement(arr, func) {
  let num = 0;
for(var i=0; i<arr.length;i++){
num= arr[i];
if (func(num)){
  return num
}
else{
   return undefined 
}
}
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Finders Keepers

Link to the challenge:

Think about the situation where the first element would not pass the truth test, but a later element would. With that else statement inside the for loop, you would return undefined in the first iteration and never make it to later element which would pass the truth test.

FYI - It is much easier to read your code if you indent it like:

function findElement(arr, func) {
  let num = 0;
  for(var i=0; i<arr.length;i++){
    num= arr[i];
    if (func(num)){
      return num
    }  
    else{
      return undefined 
    }
  }
}
1 Like

Sweet. Thanks Randell. Noted on Code Arrangement, will try. Thank you.

Two additional notes:

  1. Since you only reference num inside your for loop, you can just initialize it with the value arr[i].
  2. If no return statement is specified, a function will return undefined by default. Hint: You do not need to use return undefined in your code.
1 Like