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

后端 未结 4 1347
深忆病人
深忆病人 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:48

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

提交回复
热议问题