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

310 Views Asked by At

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){/*...*/}

2

There are 2 best solutions below

0
James Thorpe On BEST ANSWER

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];
1
Nina Scholz On

This will do it:

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

The solution prevents falsy values and returns 0 as default value. Read more here about Logical Operators.