Reputation: 9788
I noticed today that looping of JavaScript object can be done using less curly brackets.
For instance, the normal way of doing things:
// The normal way
var foo = {
bar: 1
};
for(var key in foo) {
if(foo.hasOwnProperty(key)) {
console.log(foo[key]); // prints out 1
}
}
The alternative, by dropping out extra { ... }
and it still works:
// The alternative
var foo = {
bar: 1
};
for(var key in foo) if(foo.hasOwnProperty(key)) { // <-- see :)
console.log(foo[key]); // prints out 1
}
However, I am less sure why this is possible. So my question is: when curly brackets can be omitted? I got a downvote saying "too broad" so I try to emphasize that I am not looking a million use cases, short answer suits just fine which explains the basics.
Thanks in advance!
Upvotes: 3
Views: 2814
Reputation: 83235
You can omit curly braces anytime there is only one statement.
for (var x in obj) {
console.log(x);
}
can become
for (var x in obj)
console.log(x);
but if you had
for (var x in obj) {
console.log(x);
console.log(x);
}
it would need the curly braces.
This is somewhat inconsistent. For example, it works for for
, while
and if
, but not for try
or catch
. For consistency, I always use braces.
Upvotes: 7
Reputation: 367
As far as I know there is only one case where you can omit the curly braces and that is when you only have one statement after the condition
if (condition) statement;
in your example you have omitted the curly braces from the first condition and but kept them in the second
if (condition)
if (condition) { statement; }
[Note] It is possible to omit semicolons but it is considered bad programming practice.
Upvotes: 0
Reputation: 11796
After a if
or loop (for
, while
) you can ommit the {
if you have only one statement after it. So
if (condition)
someFunction();
equals to
if (condition) {
someFunction();
}
And
if (condition) a(); b();
equals to
if (condition) {
a();
}
b();
You can even nest that:
if (condition)
while(condition2)
if (condition3)
someFunction();
For readibility it's best (read: I prefer) to always use braces (also less prone to make programming-errors).
Upvotes: 5
Reputation: 13159
As long it's one instruction you can omit curly brackets.
for(var key in foo)
if(foo.hasOwnProperty(key))
console.log(foo[key]); // prints out 1
for(var key in foo)
if(foo.hasOwnProperty(key))
for(var i=0; i<=10; i++) {
console.log(foo[key]); // prints out 1
console.log(foo[key]); // prints out 1
console.log(foo[key]); // prints out 1
}
Upvotes: 0