Concise syntax for javascript if statements without curly brackets

后端 未结 5 1542
孤街浪徒
孤街浪徒 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:15

    But why isn't using that a good idea?

    Because it's hard to maintain.

    Why can't I find any formal documentation of it? Is it not part of the spec and standard?

    Of course it is, see §12.5 - The if Statement and §12 - Statements in the spec. The body of an if is a Statement. One kind of Statement is Block (§12.1), which allows a list of statements to be treated as one statement, but there are many other kinds of statements.

    Is it not widely supported?

    Universally.

    Is it just because minification could break code using that syntax?

    A good minifier won't break that syntax. (A good minifier will make use of it, in fact.)

    What defines the contents of the if block? Is it indentation based?

    The body of an if statement consists only of the statement following it, indentation has no significance in JavaScript. So all of these are equivalent:

    if (foo)
        bar();
    charlie();
    
    if (foo) bar();
    charlie();
    
    if (foo)
    bar(); charlie();
    
        if (foo)
    bar();
        charlie();
    

    In the above, only the call to bar is conditional on foo; charlie is called regardless.

    That's why we have Block, the Statement that introduces a list of statements to be treated as a unit (a block, you might say :-) ):

    if (foo) {
        bar();
    }
    charlie();
    
    if (foo) { bar(); }
    charlie();
    
    if (foo) {
    bar(); } charlie();
    
        if (foo)
    { bar(); }
        charlie();
    

    Indentation is important for humans, though, so keeping consistent indentation is a good idea. The first example in each of the above is probably clearest (of the ones listed) for us mere mortals. :-)

    On another note, is there something similar to this syntax for if statements in PHP?

    I'm not a big PHP-head, but it looks identical, defined in Control Structures - if. There are examples with and without {}. (There's also a different, alternative syntax I won't go into here.)

    Does such an if block support having an else as well, both in JS and PHP?

    Yes, if supports else both with and without blocks.

提交回复
热议问题