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?
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.
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.
You can't break from a forEach .
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).
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With