40
loading...
This website collects cookies to deliver better user experience
const marks = [
{ name: "English", mark: 80 },
{ name: "Maths", mark: 100 },
{ name: "Science", mark: 38 },
{ name: "Social", mark: 89 }
];
let isFailed = false;
marks.forEach((subject) => {
console.log("checking subject => " + subject.name);
if (subject.mark < 40) {
// failed
isFailed = true;
}
});
console.log("Is student failed => " + isFailed);
checking subject => English
checking subject => Maths
checking subject => Science
checking subject => Social
Is student failed => true
let isFailed = false;
marks.forEach((subject) => {
// added this condition to prevent further checking
if (!isFailed) {
console.log("checking subject => " + subject.name);
if (subject.mark < 40) {
// failed
isFailed = true;
}
}
});
console.log("Is student failed => " + isFailed);
checking subject => English
checking subject => Maths
checking subject => Science
Is student failed => true
let isFailed = false;
for (i = 0; i <= marks.length; i++) {
const subject = marks[i];
console.log("checking subject => " + subject.name);
if (subject.mark < 40) {
// failed
isFailed = true;
// prevents further execution
break;
}
}
console.log("Is student failed => " + isFailed);
break
keyword. The break statement is used to jump out of a loop
Array.prototype.some()
.The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
const isFailed = marks.some((subject) => subject.mark < 40);
console.log("Is student failed => " + isFailed); // true
const isFailed = marks.some((subject) => {
console.log("checking subject => " + subject.name);
return subject.mark < 40;
});
console.log("Is student failed => " + isFailed);
checking subject => English
checking subject => Maths
checking subject => Science
Is student failed => true