xxxxxxxxxx
const array = [1, 2, 3, 4, 5];
array.forEach(item => {
if (item === 3) {
return; // Will skip the current iteration
}
console.log(item);
});
xxxxxxxxxx
//break out of for loop
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
}
xxxxxxxxxx
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
xxxxxxxxxx
The for…of loop would be the preferred solution to this problem. It provides clean easy to read syntax and also lets us use break once again.
let data = [
{name: 'Rick'},{name: 'Steph'},{name: 'Bob'}
]
for (let obj of data) {
console.log(obj.name)
if (obj.name === 'Steph') break;
xxxxxxxxxx
//Use some instead
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
xxxxxxxxxx
//Use this instead
[1, 2, 3, 4, 5].every(v => {
if (v > 3) {
return false;
}
console.log(v);
// Make sure you return true. If you don't return a value, `every()` will stop.
return true;
});
xxxxxxxxxx
const numbers = [1,2,3,4,5]
numbers.every(num => {
if (num === 3) {
return false;
}
console.log(num)
return true
})
//output : 1, 2
xxxxxxxxxx
const array = [1, 2, 3, 4, 5];
array.forEach((element) => {
if (element === 3) {
return; // Skips the element 3 and continues with the loop
}
console.log(element);
});
xxxxxxxxxx
try {
array.forEach(function(element) {
// Code inside the loop
if (/* condition to break the loop */) {
throw new Error('Loop break exception');
}
});
} catch(error) {
if (error.message !== 'Loop break exception') {
throw error; // Rethrow unexpected errors
}
}