I was going through BackboneJS source code and was unable to figure out what this line options || (options = {});
does, since there is not assignment to a variable.
Following is the code snippet from BackboneJS.
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
But there is an assignment in there:
So if
options
is falsey, theoptions = { }
part will be executed. Sinceoptions
is specified to be an object orundefined
(i.e. not passed at all), an object is truthy, andundefined
is falsey, that expression will do nothing ifoptions
is specified and setoptions = { }
ifoptions
is not passed. That expression is just a different way of writing:Keep in mind that an expression also qualifies as a statement in JavaScript so you can say things like:
in JavaScript; those two do nothing at all but
options || (options = { })
has an assignment as a side effect. Presumablyoptions || (options = { })
is evocative of theoptions ||= { }
syntax that is available in many languages — but not in JavaScript — so the notation is easy for the Backbone authors to read.