Finders Keepers - why doesn't my code work?

I know the solution has a more concise code but I don’t understand why the code I wrote doesn’t work? What am I missing?

Also - I don’t understand why the solution doesn’t return all values in the array that pass the truth test (as it is using a for loop). The challenge asks for just the first one.

solution I refer to is here: (https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers/)

Your code so far


function findElement(arr, func) {

let trueArr = [];

for(let i = 0; i < arr.length; i++){
  if(func(arr[i] = true)){
    trueArr.push(arr[i]);
    return trueArr[0];
  } 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/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers

Your code has two issues:

1st issue is the following statement:

if(func(arr[i] = true)){

The above sets the value of arr[i] to true and then func is called passing the value true to it. I am sure this is not what you want to do.

2nd issue (assuming you fix the above statement) is that your function will only look at the first element in arr before returning the value 1 (the first element in arr) or undefined.

Remember when a return statement is executed, the function immediately exits. Think about when/where you should really use the return undefined statement.

Thanks for that.

I’ve amended the code to correct the function and change location of return function.

I don’t understand why it’s still not working. What am I missing?

function findElement(arr, func) {
let trueArr = [];

for(let i = 0; i < arr.length; i++){
  if(func(arr[i]) == 1){
    trueArr.push(arr[i]);
    
  } 
  
  else {return undefined;}
}


return trueArr[0];
}

remember that when you have an else statement at the end, one of the statements in the chain will always execute - you have a return statement inside the loop and a return statement will break from the function returning a value, you have a return undefined that will run as soon as the if condition is false

remember that func(arr[i]) returns a boolean, so you may want to compare it with true or false not with a number