6

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 ?

Ilja
  • 1,205
  • 1
  • 16
  • 33

2 Answers2

14

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.

Tirthraj Barot
  • 2,671
  • 2
  • 17
  • 33
7

There is no need for forEach when you want to break on the first occurrence. Just use find() instead.

 status = states.find((messageEntity) => 
     messageEntity.id == message.id && messageEntity.is_question == message.is_question
 ).status;
str
  • 42,689
  • 17
  • 109
  • 127
  • Should be marked as answer IMO – Alex Jan 12 '18 at 14:03
  • unless you need to support really old browsers (IE11 and less), IE mobile, opera mini, etc ... https://caniuse.com/#search=find – Eclectic Aug 21 '19 at 00:59
  • Then just use a [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill). – str Aug 21 '19 at 08:23