2

I have the code below. I am purposefully trying to use forEach in this instance.

function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)

I am expecting the code to return true because the el value of 3 is in the array. But instead it returns undefined. What am I doing wrong?

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
PineNuts0
  • 4,740
  • 21
  • 67
  • 112

4 Answers4

5

forEach don't return anything ( means undefined ), you can use some

function check(arr, el) {
  return arr.some( element => element === el)
}

console.log(check([1, 2, 3, 4, 5], 3))

If you want to use forEach than use a variable to store value and than return later from function

function check(arr, el) {
  let found = false
  
  arr.forEach((element) => {
    if (element === el && !found){
      found = true
    }
  })
  return found
}



console.log(check([1, 2, 3, 4, 5], 3))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
4

Cannot use return inside a forEach statement.

NOTE: This answer is only because you need to use forEach. Ordinarily you would always use some().

function check(arr, el) {
  let found = false;
  arr.forEach((element) => {
    console.log(element)
    if (element === el) {
      found = true;
    }
  });
  return found;
}



console.log( check([1, 2, 3, 4, 5], 3));
Bibberty
  • 4,670
  • 2
  • 8
  • 23
0

Just to use OP's context. since one has to use forEach.

function check(arr, el) {

  let found = false;

  arr.forEach((element) => {
    console.log(element)
    if (element === el){
        found = true;
    }
  })

  return found;
}
Ji_in_coding
  • 1,691
  • 1
  • 14
  • 17
0

If you want to use forEach you need to have a variable being updated when you find a match. Array.forEach by default returns undefined. There is no build in way to break out of the forEach.

Since you are just looking for a simple element match simply use Array.includes:

let check = (arr, el) => arr.includes(el)

console.log(check([1, 2, 3, 4, 5], 3))

Array.some gives you an iterator function which in this case you really do not need.

With Array.forEach:

function check(arr, el) {
  let result = false
  arr.forEach((element) => {
    if (element === el) {
      result = true  // <-- update the result on match
    }
  })
  return result  // <-- return the result
}

console.log(check([1, 2, 3, 4, 5], 3))
Akrion
  • 18,117
  • 1
  • 34
  • 54