Zahema Zahema - 9 months ago 24
Javascript Question

What does that javascript syntax do?

what would

equal? and why?

In other words, how Boolean operators work with objects?

var data = {x:123, y:456};
var r = data && data.x || 0;


when I run it
always equals
, but I didn't understand why.


From MDN,

Javascript uses type coercion in Boolean contexts.

There are 8 "falsy" values in Javascript

  • false
  • null
  • undefined
  • 0
  • NaN
  • ''
  • ""
  • document.all

In your example, data && data.x || 0, the && and || make this a Boolean context. data is coerced to a Boolean. If it is not one of the values listed above it is coerced to true.

Programmers often check to see if an object is defined (i.e. not null and not undefined) by checking to see if the value is "falsy". Your example could be rewritten as

var r = 0;
if(data && data.x){
  r = data.x;

Which I think makes it clear that you are checking to see if data is defined and data.x is not falsy (e.g. 0). This is a common technique to avoid null reference errors if you are unsure if the variable contains a valid object or not.