Why is it that when i assign num = arr[i]; and return it ,it doesnot work but when i simply return arr[i] it works?

Tell us what’s happening:
Describe your issue in detail here.

Why is it that when i assign num = arr[i]; and return it ,it doesnot work but when i simply return arr[i] it works ?

  **Your code so far**

function findElement(arr, func) {
 let num;

for (let i = 0; i < arr.length; i++) {
  if (func(arr[i])) {
    num = arr[i];
  }
}

return num;
}

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/91.0.4472.77 Safari/537.36

Challenge: Finders Keepers

Link to the challenge:

you must return the first element which matches the criteria. Your loop keeps updating the num value with any subsequent element in the array which matches the criteria

1 Like

Yeah, you have the right idea, you just need to rethink where that return statement should go.

2 Likes

Thank you! The first num i declared was not even used and still faded when i used num = arr[i]; so i was really confused and thought was it because of block scoped ‘let’. So is it just because of how the question is designed and what i did is right too?

Thank you! The first num i declared was not even used and still faded when i used num = arr[i]; so i was really confused and thought was it because of block scoped ‘let’. So is it just because of how the question is designed and what i did is right too?

The question states “returns the first element in it that passes a ‘truth test’.” Your code will always go through all the elements and return the last element that passes the truth test.

You can tell what is happening by adding a console.log inside the if statement in the for loop:

...
  if (func(arr[i])) {
    num = arr[i];
    console.log(num);
  }
...

and you will see num is still valid, it is simply being reassigned each time func(arr[i] evaluates to true, instead of returning the very first one.

1 Like

Well, the “num” variable, I would say that it isn’t really needed. I would just return the value I want from where I find it without storing it. There is another way to do it where you store the value, break out of the loop, and return the value store in num at the bottom. That is a valid way to do it, but I would still prefer the first - unless things were more complicated and there was a reason to store the value.

But either would work. All of the answers here are giving you good advice.

1 Like