I hope someone can answer this for me. Is there a way in JavaScript that we can use a loop with an "if" statement inside and only return true if all the values in the loop iterations meet that condition. Thank you
I hope someone can answer this for me. Is there a way in JavaScript that we can use a loop with an "if" statement inside and only return true if all the values in the loop iterations meet that condition. Thank you
Share Improve this question asked Dec 14, 2019 at 15:12 Zaeem Jalil MalikZaeem Jalil Malik 311 silver badge3 bronze badges 1-
for (…) { if (!condition) return false; } return true
– Bergi Commented Dec 14, 2019 at 15:23
2 Answers
Reset to default 6Yes there is. For example the .every
method of an Array does this exact thing.
Quoted from MDN:
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
const ages = [24, 32, 22, 21, 29];
const legalDrinkingAge = 21;
const areLegalDrinkingAges = ages.every(age => age >= legalDrinkingAge);
console.log(areLegalDrinkingAges);
You can define a var, e.g. result
holding the value true
, then executing the for loop and checking the condition using the if
statement. Once condition fails, set result
to false
and break out of the for
loop.
At the end, result
will be true
if the if
statement was true for all elements checked and false
otherwise.
var result = true;
var a = [12,14,16,18,5,11,12]; // array with example values
for (var i = 0; i < a.length; i ++) {
if (!(a[i] >= 10)) { // the condition
result = false;
break;
}
}
console.log(result); // false