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

后端 未结 10 938
忘掉有多难
忘掉有多难 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:10

    Why not something more simple, like:

    a = a || 0;
    

    or

    a = a ? a : 0;
    

    In both of these cases, you can also clearly see that something is being assigned to a, right at the start of the line, without resorting to reading the whole thing, and figuring out if there are any game-changing function-calls happening on either the left or right side... or figuring out what both sides do, in general, to decide how many potential program-wide changes there might be.

    If you need to include the whole type-check, it's still not that large.

    a = (typeof a !== "undefined") ? a : 0;  // [parentheses are there for clarity]
    

提交回复
热议问题