PineNuts0
PineNuts0

Reputation: 5234

JavaScript: Use forEach to see if array contains a specific number value

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?

Upvotes: 1

Views: 12827

Answers (4)

Akrion
Akrion

Reputation: 18525

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))

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

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))

Upvotes: 5

Bibberty
Bibberty

Reputation: 4768

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));

Upvotes: 3

Ji_in_coding
Ji_in_coding

Reputation: 1701

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;
}

Upvotes: 0

Related Questions