P
Pedro Pinheiro
Hey folks,
One thing I've been wondering about lately is how to write a for (key in object) loop in a nice, idiomatic manner.
What to me seems the obvious shape for it is
for (key in object) {
if (object.hasOwnProperty(key)) {
doStuff();
}
}
but that is a wee bit too verbose, and eats up an indent level unnecessarily. I've also seen the form
for (key in object) {
if (!object.hasOwnProperty(key)) {
continue;
}
doStuff();
}
which doesn't eat up the extra indent level, but is longer, and suffers from not making it quite as obvious that the if is filtering the keys. I've personally come to favour
for (key in object) if (object.hasOwnProperty(key)) {
doStuff();
}
Which, to my eyes, is nice and compact, but I really haven't seen it anywhere else, so fails a bit on the
surprise factor for anyone else reading my code.
So, what do you guys like, and why?
One thing I've been wondering about lately is how to write a for (key in object) loop in a nice, idiomatic manner.
What to me seems the obvious shape for it is
for (key in object) {
if (object.hasOwnProperty(key)) {
doStuff();
}
}
but that is a wee bit too verbose, and eats up an indent level unnecessarily. I've also seen the form
for (key in object) {
if (!object.hasOwnProperty(key)) {
continue;
}
doStuff();
}
which doesn't eat up the extra indent level, but is longer, and suffers from not making it quite as obvious that the if is filtering the keys. I've personally come to favour
for (key in object) if (object.hasOwnProperty(key)) {
doStuff();
}
Which, to my eyes, is nice and compact, but I really haven't seen it anywhere else, so fails a bit on the
surprise factor for anyone else reading my code.
So, what do you guys like, and why?