JavaScript open brace in the same line

后端 未结 6 1574
心在旅途
心在旅途 2020-12-16 03:50

I remember there is a convention/recommendation to put opening brace in the same line, because of the way JavaScript adds a semicolon or something.

//OK
fun         


        
6条回答
  •  误落风尘
    2020-12-16 04:35

    Douglas Crockford gives a reason for choosing the K&R style [1]:

    "I always use the K&R style, putting the { at the end of a line instead of the front, because it avoids a horrible design blunder in JavaScript's return statement.

    The blunder he is referring to is how JavaScript handles the return statement differently in the following two scenarios:

    return {
       'status': 'ok'
    };
    

    ... and:

    return 
    {
       'status': 'ok'
    };
    

    The first one will return an object with a status property, while the latter will return undefined because of semicolon insertion."

    [1] Douglas Crockford: JavaScript: The Good Parts: Style (p. 96)

提交回复
热议问题