28

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?

6
  • 1
    What loop? for (var i = 0... etc, a literal .forEach or what? Commented Oct 5, 2016 at 20:12
  • What loop? I see json but no javascript. Commented Oct 5, 2016 at 20:12
  • 1
    Just say break; inside of the forloop inside of the if statement that checks for the NULL value. Commented Oct 5, 2016 at 20:12
  • 2
    After update: yes, it's a duplicate of what Robbie reported. Commented Oct 5, 2016 at 20:15
  • 1
    I did checkout stackoverflow.com/questions/2641347/… 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. Commented Oct 5, 2016 at 20:54

1 Answer 1

80

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
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

What if one can only use foreach?
Why can you only use .forEach?
for in doesn't work for a Map. for of is not available in ES5. for(i=0; i<n; i++) needs to get values first, i.e. map.values(), I'm not sure if it harms performance because our WebGL app needs to loop through the map values every frame.
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).
you can also change the length of the array itself, this will cause the forEach to break
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.