Multiple assignments var a = b = b || {} in javascript

Reading the sheetlet.js file, I came across a method with this line that I do not quite understand:

var events = this._leaflet_events = this._leaflet_events || {}; 

which can be simplified as

 var a = b = b || {}; 

From what I understand, this instruction is a multiple left assignment, which is a correct associative, which means that firstly, JavaScript will work

 b = b || {} //if b exists, returns b, else return an empty object 

then

 a = b // returns the output of the preceding instruction 

That doesn't make sense to me. Why not write instead:

 a = b || {}; 

Full context:

 addEventListener: function( /*string*/ type, /*function */ fn, /*(optional) object*/ context){ var events = this._leaflet_events = this._leaflet_events || {}; events[type] = events[type] || {}; events[type].push({ action: fn, context: context || this }); return this; } 

I suspect a reference trick, because I don't see how this._leaflet_events will be changed in another way.


Thinking about it, write var a = b = b || {} var a = b = b || {} is actually a trick to assign var a reference to b , whether b defined or not. Changing a now changes b .

Return to Leaflet. Through

  var events = this._leaflet_events = this._leaflet_events || {}; 

this._leaflet_events either exists or is initialized to the value {} . events assigned to this._leaflet_events by reference. The initial value may be {} , but when events change, it changes this._leaflet_events .

On the contrary, record

  var events = this._leaflet_events || {}; 

will be an error, since if this._leaflet_events not defined, events will now point to a newly created object whose value will be {} . Changing events will change the new object, but will not change the value of this._leaflet_events .

The same meanings, different links. That's what.

+7
source share
2 answers

A shorter expression will not set anything as the value of b

 a = b = b || {}; //set bb value to {} if b is uncdefined, then set a value to b a = b || {}; //set a value to b, or {} if b is undefined 

the first statement is actually equivalent

 b = b || {}; a = b; 
+7
source

Statement var a = b = b || {}; var a = b = b || {}; does two things:

  • Initializes b to {} if it was undefined.
  • It sets the same as b.

The expression a = b || {}; a = b || {}; does not change b, therefore it is not equivalent.

+10
source

All Articles