javascript - Why is it common practice in JS libraries to duplicate variable name and adding 'or object' -


i trying better grip on js syntax , wondering why common practice in many libraries repeat object name after variable same name has been declared. please see below:

var backbone = backbone || {};    // <= why duplication? 

or

var listeners = this._listeners || (this._listeners = {}); 

update:

after further research have found written article evaluates many idiomatic expressions.

the article explains use behind invoked function expressions (iife), i.e wrapping of function within function, such:

(function() {   console.log('hello!'); })(); 

which 1 of js brainteasers newbies me can't quite understand.

var backbone = backbone || {}; 

means if backbone undefined or null or false, set {}


longer explanation:

the assignment operator evaluates right left , logical operators(even though javascript doesn't have real logical operators work on non-boolean operands well) evaluate left right.

an expression a || b returns b if a undefined, null, or false.

so a = || b either keeps a value if has 1 or assigns b a.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -