0

I am going through a challenge on Freecodecamp and solved this problem, however I am not sure of some of the logic and just want to clarify

Please see below code

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

console.log(findElement([1, 2, 3, 4], num => num % 2 === 0))

I have 2 main questions

  1. The console only logs 2 in this instance. Why would my for loop not continue and also log 4

  2. Also, I understand why it logs a even number but then once this happens why does the code not move on to the next line and log undefined?

  3. I initially put in a else statement to say following the loop else {return undefined;} though this didn't work and the return statement has to be outside of the for loop which I dont quite understand?

Thanks for the help on this one :)

Wattlebird
  • 21
  • 4
  • 1
    `return` statement just immedieately leaves the function with value you have provided. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return – Jan Pfeifer Jan 31 '23 at 14:04
  • Re the third of your 2 main questions ;-) `else` can only appear after an `if`, not after a looping construct like `for`, which is why you got an error. Also, as a side note: *Usually* in this sort of thing you'd only care that `func` returned a [truthy value](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), not specifically `true`. So just `if (func(arr[i])) { return arr[i]; }` Finally, in newer code that doesn't need the loop index, prefer `for-of` to `for` with `length` -- [more here](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript). – T.J. Crowder Jan 31 '23 at 14:11
  • ["*logs*"](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) and "*returns*" are 2 different things, if you were to remove the [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) statement and instead `console.log` the `arr[i]` you will see it logs the even numbers. Next, `else` statement returns `undefined` just as fine if first number in the array is odd, not sure what issue you encountered there? – Aleksandar Jan 31 '23 at 14:22

0 Answers0