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
  • 35,187
  • 4
  • 31
  • 54
PineNuts0
  • 4,050
  • 16
  • 57
  • 93

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
  • 35,187
  • 4
  • 31
  • 54
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,508
  • 2
  • 7
  • 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,601
  • 1
  • 12
  • 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
  • 17,012
  • 1
  • 30
  • 48