Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out from foreach loop in javascript [duplicate]

Tags:

I am newbie in Javascrript. I have a variable having following details:

var result = false; [{"a": "1","b": null},{"a": "2","b": 5}].forEach(function(call){     console.log(call);     var a = call['a'];     var b = call['b'];     if(a == null || b == null){         result = false         break;     } }); 

I want to break the loop if there is NULL value for a key. How can I do it?

like image 786
Sahil Avatar asked Oct 05 '16 20:10

Sahil


People also ask

How do you break out of a forEach loop?

To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection.

Can we break forEach loop in JavaScript?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Can we use break statement in forEach?

You can't break from a forEach .

How do you exit a for loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).


1 Answers

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}] var result = false  for(var call of myObj) {     console.log(call)          var a = call['a'], b = call['b']           if(a == null || b == null) {         result = false         break     } } 
like image 93
Fathy Avatar answered Oct 06 '22 00:10

Fathy