[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method in JavaScript? I’ve tried return;, return false; and break. break crashes and return does nothing but continue iteration.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no built-in ability to
breakinforEach. To interrupt execution you would have to throw an exception of some sort. eg.JavaScript exceptions aren’t terribly pretty. A traditional
forloop might be more appropriate if you really need tobreakinside it.Use
Array#someInstead, use
Array#some:This works because
somereturnstrueas soon as any of the callbacks, executed in array order, returntrue, short-circuiting the execution of the rest.some, its inverseevery(which will stop on areturn false), andforEachare all ECMAScript Fifth Edition methods which will need to be added to theArray.prototypeon browsers where they’re missing.Use
Array#every