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?
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;
}
}