Can someone give me some insight as to why the first 2 functions return undefined instead of a boolean?
https://jsfiddle.net/wjf2gr9d/
const array1 = [1, 2, 3];
const test1Result = test1();
const test2Result = test2();
const test3Result = test3();
console.log(test1Result);
console.log(test2Result);
console.log(test3Result);
function test1() {
return array1.forEach(x => 2 === x);
}
function test2() {
const found = array1.forEach((x, index) => {
if (2 === x) {
return true;
}
return false;
});
return found;
}
function test3() {
const maybeTeam = array1.find(x => 2 == x);
return (maybeTeam) ? true : false;
}
If you check this check return value section it returns undefined.

Foreach doesn't have any return types, You can use some. If you must use foreach then you can take temp variable and change it inside foreach like I did in test2
const array1 = [1, 2, 3];
const test1Result = test1();
const test2Result = test2();
const test3Result = test3();
console.log(test1Result);
console.log(test2Result);
console.log(test3Result);
function test1() {
return array1.some(x => 2 === x);
}
function test2() {
var found = false;
array1.forEach((x, index) => {
if (2 === x) {
found = true;
}
});
return found;
}
function test3() {
const maybeTeam = array1.find(x => 2 == x);
return (maybeTeam) ? true : false;
}
forEach always returns undefined; return <arr>.forEach will always result in undefined being returned, no matter the logic in the forEach. If you want to check whether any item in an array passes a particular test, you should use .some instead:
const array1 = [1, 2, 3];
const test1Result = test1();
console.log(test1Result);
function test1() {
return array1.some(x => 2 === x);
}
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