简体   繁体   中英

JavaScript: When we can omit curly brackets?

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!

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).

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.

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
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM