In Javascript, is it OK to put the ternary operator's `?` on then next line?

后端 未结 4 1353
深忆病人
深忆病人 2021-02-01 15:08

I really like aligning the ? and the : of my ternary operator when they don\'t fit on a line, like this:

var myVar = (condition
    ? ifTrue
    : ifFalse
);
         


        
4条回答
  •  心在旅途
    2021-02-01 15:49

    UPDATE: This answer is outdated now. Apparently Crockford changes his mind ;)

    See @CheapSteaks's answer for the update.

    Per Crockford:

    Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.

    So:

    // this is ok
    var myVar = (condition ?
        ifTrue : 
        ifFalse
    );
    

    If you run this sample code through JSHint, this will pass:

    // this is ok
    var myVar = (1==1 ?
        true : 
        false
    );
    

提交回复
热议问题