Concise syntax for javascript if statements without curly brackets

后端 未结 5 1547
孤街浪徒
孤街浪徒 2021-01-18 06:56

So pragmatically, I\'ve got a quick and dirty answer to what I\'m looking for here. But why isn\'t using that a good idea? Why can\'t I find any formal documentation of it

5条回答
  •  爱一瞬间的悲伤
    2021-01-18 07:23

    It is standard, part of the spec (if-statement, other statements) and supported everywhere. Minification does not break it, because whitespaces have no semantics in JS - it even will enforce it for one-line-statements to save the two braces.

    So, it is widely used (without problems!) as well. Sometimes it is considered bad because appending statements to the indented body without adding the braces can lead to problems. Also, it can lead to erratic behaviour when used in nested ifs:

    if (false)
        if (whatever)
             ;
    else
        alert("");
    

    Would you have expected an alert? No, the else belongs to the last if.

    Yet, you can use it unconcerned for one-line-statements that are sure not to get extended, like return;.

提交回复
热议问题