Javascript variable

Please explain to me what this line of code does:

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

My best guess:

It sets the variable "list" with the value calls.xxx, where xxx is the variable ev. If the call [ev] does not exist, then it creates it as an empty object and assigns this empty object "list". Is it correct?

Why are parentheses used? Where can I find out more about using || when setting variables and using parentheses in this context? Thanks!

+8
javascript variables fallback
source share
4 answers

This code is equivalent

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

Two language features are used:

  • Calculation of fast calculations of Boolean expressions (consider a || b . If a - true , then b not evaluated). Thus, if you assign var v = a || b; var v = a || b; and a value for something that can be added to true , then b not evaluated.
  • The assignment operator calculates the last assigned value (to include var a = b = c; )

Parentheses are needed to avoid this interpretation:

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

(which is a mistake).

+8
source share

Your guess is correct. This is the usual way to declare default values ​​for variables in JavaScript.

 function foo(bar) { var bar = bar || 0; //This sets bar to 0 if it not already set console.log(bar); } 

How this works is that in JavaScript, the undefined variable is false, which means that in any comparaison boolean operation, it will evaluate to false . Then you can use the OR operator to combine the two values, and it will return the first value, which evaluates to true .

+5
source share

|| or 'logical OR' has a higher precedence than the assignment operator = , so parentheses are needed to make sure this idiom is evaluated in the correct order

Another thing to keep in mind is that many languages, including Javascript, provide a short circuit assessment for logical operators such as AND and OR. If the first operand is boolean or evaluates to true, there is no need to evaluate the second operand because it has no meaning for the result.

Understand this, and you will see that this is not some special assignment syntax, but an idiom or template that uses a language function to provide a more compact representation of the idea.

+1
source share

you are right in your first guess. This is a generic template for initializing javascript namespaces. It serves to ensure that you do not overwrite the previous object with the same name. Most popular libraries will do something similar to create their namespace objects.

The brackets are that the expressions are evaluated in the correct order.

+1
source share

All Articles