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

落爺英雄遲暮 提交于 2019-12-20 11:49:40

问题


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

However, JSHint complains with:

Bad line breaking before '?'

Why would JSHint have this warning? Is there any nastyness (like semicolon insertion, etc) it is protecting me against or can I safely change my JSHINT configuration to ignore it?


回答1:


This works and is certainly valid. It's especially useful in more complicated use cases, like nested ones.

var a = test1
         ? b
         : test2
            ? c
            : d;



回答2:


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




回答3:


Per Crockford

The ternary operator can be visually confusing, so ? question mark always begins a line and increase the indentation by 4 spaces, and : colon always begins a line, aligned with the ? question mark. The condition should be wrapped in parens.

var integer = function (
    value,
    default_value
) {
    value = resolve(value);
    return (typeof value === "number")
        ? Math.floor(value)
        : (typeof value === "string")
            ? value.charCodeAt(0)
            : default_value;
};



回答4:


You should put the operator on the end of the line. That way its more clear that the statment continued to the next line.



来源:https://stackoverflow.com/questions/7259065/in-javascript-is-it-ok-to-put-the-ternary-operators-on-then-next-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!