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.
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With