Search code examples
javascriptif-statementshorthandshorthand-if

Value variable as 0 not as false in shorthand-if expression


I'm calling a function in either those two ways

foo([x,y]) or foo({x:x,y:y}) with x,y ∈ [0,∞)

the foo function looks like this

var x = pos.x || pos[0],
    y = pos.y || pos[1];

If I call the function the second way with x=0 then pos.x will be valuated as false, which leaves x=pos[0] that is undefined.

I wondered whether there is way for 0 not valuated as false like in the longhand method with if(pos.x===0){/*...*/}


Solution

  • You need to check if pos.x exists, rather than by checking it's value. You can do this with the hasOwnProperty function:

    var x = pos.hasOwnProperty('x') ? pos.x : pos[0];