26

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?

Sahil
  • 491
  • 2
  • 9
  • 18
  • 1
    What loop? `for (var i = 0...` etc, a literal `.forEach` or what? – VLAZ Oct 05 '16 at 20:12
  • What loop? I see json but no javascript. – Igor Oct 05 '16 at 20:12
  • 1
    Just say `break;` inside of the forloop inside of the if statement that checks for the NULL value. – Nicholas Siegmundt Oct 05 '16 at 20:12
  • 2
    After update: yes, it's a duplicate of what Robbie reported. – VLAZ Oct 05 '16 at 20:15
  • 1
    I did checkout http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break link. However, I was not able to figure out the solution. Given link has simple(int,string) array. In my array I have object and need to check whether any property has null value. – Sahil Oct 05 '16 at 20:54
  • `var result = arr.every(obj => obj.a ===null || obj.b === null)` that's it. The second answer already mentions `.every` and all you need then is the check. – VLAZ Oct 05 '16 at 20:58

1 Answers1

74

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
    }
}
Fathy
  • 4,939
  • 1
  • 23
  • 25
  • 1
    What if one can only use `foreach`? – zwcloud May 18 '18 at 09:17
  • 2
    Why can you only use `.forEach`? – Fathy May 18 '18 at 09:18
  • `for in` doesn't work for a `Map`. `for of` is not available in ES5. `for(i=0; i – zwcloud May 18 '18 at 09:26
  • 4
    If you care about performance use `.forEach` and ignore next calls when you have your result, this is the most efficient way to do it in ES5. Note that ES5 doesn't have `Map` so your are probably using a polyfill like `core-js`, native objects (`{}`) are faster in this case and can be iterated using `for(var key in object)`. – Fathy May 18 '18 at 10:51
  • 1
    you can also change the length of the array itself, this will cause the forEach to break – kumail Mar 07 '21 at 04:02