[removed] || instead of IF statement - is this legal and cross browser valid?

后端 未结 10 950
忘掉有多难
忘掉有多难 2020-12-23 20:43

It seems that:

if (typeof a == \'undefined\') {
    a = 0;
}

and

(typeof a != \'undefined\') || (a = 0)

h

10条回答
  •  暖寄归人
    2020-12-23 21:26

    is this legal, and cross browser valid?

    Yes, it will work in all EcmaScript engines. However, it is very uncommon to (ab)use short-circuit-evaluation as an if-statement.

    I mean, jslint says it has errors. Should I use it without concerns?

    No, JsLint is right. It is unusual and confusing, at least to other developers. It looks too much like an OR-condition - yet is has no "body". And if you do assignments, the variable is expected to be on the beginning of the statement, not inside some expression.

    I really like the second one because it is short, one line code

    Then use

    if (typeof a == 'undefined') a = 0;
    

提交回复
热议问题