Question regarding Finders Keeper

Dear all,

I have few questions regarding this code:

  1. Even though I know by deleting the else statement and add the return undefined before the last curly bracket is the right answer. I’m wondering why the else statement will not work here.
  2. The code here:
for(let i=0; i<arr.length; i++){
  num = arr[i]
  if(func(num)){
    return num

If there are more than one arr[i] fulfill the requirement, won’t it return all of them?
If not, why?
Thanks for answering.

Full code


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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15

Challenge: Finders Keepers

Link to the challenge:

You are iterating through the array. the else statement will immediately return undefined if the first element in the array doesnt pass the test. Means it will end the iteration at i=0 , even though there is elements in the array which will pass the test

so you should add the return undefined statement outside the loop.Means only return undefined if all the items in the array fail the test.

Every function will end its execution at the moment it sees a return statement. Even there are codes after return statement that wont be executed

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