2

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

InsOp
  • 1,446
  • 2
  • 19
  • 31
  • `||` is a binary operation which can only deal with `Boolean` values. If any other value is provided then its converted to Boolean value and then operation is performed. `Number 0` or `String ''` is considered as `Boolean False` – Rayon Sep 21 '15 at 11:03

2 Answers2

3

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];
James Thorpe
  • 28,613
  • 5
  • 64
  • 82
1

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.

Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
  • Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. – SuperBiasedMan Sep 21 '15 at 11:39