I normally use this pattern to iterate over object properties:
for(var property in object) {
if(object.hasOwnProperty(property)) {
...
}
}
I don't like this excessive indentation and recently it was pointed out to me that I could get rid of it by doing this:
for(var property in object) {
if(!object.hasOwnProperty(property)) {
continue;
}
...
}
I like this because it doesn't introduce the extra level of indentation. Is this pattern alright, or are there better ways?
while loop, condition is checked at the end of each iteration of the loop, rather than at the beginning before the loop runs. This means that code in a do... while loop is guaranteed to run at least once, even if the condition expression already evaluates to true .
If you would like to iterate directly over the values of the keys of an object, you can define an iterator , just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set. JS will attempt to iterate via the default iterator property, which must be defined as Symbol. iterator .
The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.
I personally prefer:
for(var property in object) if(object.hasOwnProperty(property)) {
...
}
There is no extra level of indentation because for
, if
, etc. will take the next statement if you leave out the curly braces. Since we put all of our code inside the if hasOwnProperty
block it makes any braces for the for
statement unnecessary.
Essentially it's equivalent to:
for(var property in object) {
if(object.hasOwnProperty(property)) {
...
} else {
continue;
}
}
Syntacticly I'd prefer something like this
function own(obj) {
var ownprops = {};
for (var prop in obj)
if (obj.hasOwnProperty(prop)) ownprops[prop] = 1;
return ownprops;
}
for (var property in own(object)) {
//code
}
Looks nice, but it entails two loops over the same object, not pretty performance wise.
The other way to do it is functionaly
function foreach(obj, func, thisp) {
for (var prop in obj)
if (obj.hasOwnProperty(prop)) func.call(thisp, obj[prop], prop);
}
foreach(object, function(val, key) {
//code
});
Only one loop, but a function is called for every iteration, which is not great performance wise but better than the last solution. Note that it also clobbers the value of this
, but you can pass that value explicitly as the optional 3rd argument.
Just some alternatives. The way you are doing it, and the way explained by Daniel is just fine, and without performance compromises.
Also, I'd like to point out that you do not have to indent your code for every single curly brace...
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