For break

Classical for loop.. nothing to talk about it.

let a = [0,1,2,3,4,5];
for (let ii = 0; ii < a.length; ii++) {
    console.log(a[ii]); //0,1,2
    if (a[ii] == 2)
        break;
}

Some loop

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.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

[0,1,2,3,4,5].some(x => {
    console.log(x); //0,1,2
    return x == 2;
});

For each

The forEach() method executes a provided function once for each array element. There’s no built-in ability to break in forEach. To interrupt execution use some loop.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/foreach

//nasty code - use some function instead
try {
    [0,1,2,3,4,5].forEach(x => {
        console.log(x); //0,1,2
        if (x == 2) throw "end loop";
    });
} catch (e) { 
    console.log(e); //end loop
}

Categories: Js,Ts,Css

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.