JavaScript Variable fallback

thugsb picture thugsb · Mar 6, 2012 · Viewed 17k times · Source

Please can someone explain to me what this line of code does:

var list  = calls[ev] || (calls[ev] = {});

My best guess:

It's setting the variable "list" with the value of calls.xxx, where xxx is a variable, ev. If calls[ev] doesn't exist, then it's creating it as an empty object and assigning that empty object to "list". Is that right?

Why are the parenthesis being used? Where can I find out more info on using || when setting variables, and the use of parenthesis in this context? Thanks!

Answer

Alexander Pavlov picture Alexander Pavlov · Mar 6, 2012

This code is equivalent to

var list;
if (calls[ev])
  list = calls[ev];
else {
  calls[ev] = {};
  list = calls[ev];
}

Two features of the language are used:

  1. The shortcut computation of boolean expressions (consider a || b. If a is true then b is not evaluated). Thus, if you assign var v = a || b; and a evaluates to something that can be cast to true, then b is not evaluated.
  2. The assignment statement evaluates to the last assigned value (to enable var a = b = c;)

The parentheses are necessary to avoid this interpretation:

var list = (calls[ev] || calls[ev]) = {};

(which is an error).