Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement not working inside foreach loop javascript

I am trying to return the first value which is greater than 25 from an array, without using other methods such as filter. Assume the array is always sorted.

The function always returns undefined. Why is that happening? Here is the code:

function checkArr(arr){
  arr.forEach(i => {
    if (i>25) return i;
  })
}

console.log(checkArr([10,20,34,45]))

The output should be 34.

like image 413
Elon Musk Avatar asked Dec 05 '22 11:12

Elon Musk


2 Answers

When you use forEach, you execute another function for every item in the array. That function can return a value just fine, but it'll get completely ignored. If you want to return a value in the checkArr function, you have to do something like this:

function checkArr(arr) {
  for (let i of arr) {
    if (i>25) return i;
  }
}
like image 161
houfio Avatar answered Dec 25 '22 23:12

houfio


You can use find function instead of forEach. And you must return a result of this function to get an answer instead of undefined.

function checkArr(arr) {
  return arr.find(i => i > 25);
}

console.log(checkArr([10,20,34,45]))

forEach function returns nothing, it just makes some actions for each element in an array.

like image 23
Daria Pydorenko Avatar answered Dec 25 '22 22:12

Daria Pydorenko