Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use break in forEach in javascript? [duplicate]

In reactjs-babel app i occurred strange behavior trying to use break in forEach

    var SomeElement = React.CreateClass({
        ... ,
        getMessageStatus: function getMessageStatus(message) {
            var states = this.state.messages_states;
            var status = undefined;
            states.forEach(function (messageEntity) {
                if (messageEntity.id == message.id && messageEntity.is_question == message.is_question) {
                    status = messageEntity.status;
                    break; // - this is not working 
                }
            });
            return status;
        },
        ...
        });

the break saids it Cannot determine target for 'break' in PhpStorm and Babel repl tells like repl: Unsyntactic break how to use break properly ?

like image 268
Ilja Avatar asked Jun 16 '16 11:06

Ilja


1 Answers

There is no in-built ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.

var BreakException= {};

try {
    [1,2,3].forEach(function(el) {
        if(el === 1) throw BreakException;
    });
} catch(e) {
    if (e!==BreakException) throw e;
}

JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.

Instead, use of Array#some:

[1,2,3].some(function(el) {
    return el === 1;
});

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.

like image 142
Tirthraj Rao Avatar answered Sep 30 '22 18:09

Tirthraj Rao