Reading leaflet.js ‘s code, I came across a method with this line which I don’t fully 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-handed assignment that is right associative which means that first, JavaScript will run
b = b || {} //if b exists, returns b, else return an empty object
, then
a = b // returns the output of the preceding instruction
Which does not 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 since I don’t see how this._leaflet_events gets modified by the method otherwise.
Thinking about it, writing var a = b = b || {} is actually be a trick to assign var a a reference to b, no matter whether b is defined or not. Modifying a now modifies b.
Back to Leaflet. With
var events = this._leaflet_events = this._leaflet_events || {};
this._leaflet_events either exists or is initialized to {}.
events is assigned this._leaflet_events by reference. The reference’s value might be {} but it is still this._leaflet_events that is being modified when modifying events.
On the contrary, writing
var events = this._leaflet_events || {};
would be a mistake , since if this._leaflet_events is not defined, events will now point to a newly created object whose value will be {}. Modifying events will change the new object but it won’t change this._leaflet_events‘s value.
Same appearent values, different references. Here is the thing.
The shorter expression will not set anything as b’s value
the first statement is in fact equivalent to