1

I'm trying to better understand BackboneJS by reading the annotated source.

options || (options = {});

Options is an attribute passed into a function, so presumably could be 'undefined'. My initial thoughts were that this statement would set options to an empty object if it was undefined. However my experimenting seemed to tell me this is not the case. Also, the previous line is this:

var attrs = attributes || {};

Which I believe does pretty much what I'd described (whilst also shortening the attribute name).

My question is, what is the actual purpose of the first code snippet?

Full context is here

tommypyatt
  • 518
  • 3
  • 13

2 Answers2

3

This line:

   options || (options = {});

Checks if options is undefined. If it is then it it assigns a new object value to options.

After the line occurs:

1.options will not be undefined.
2.The left hand sign(if exists) will be assigned with options.

This is the same as

options = options || {};


This line:

var attrs = attributes || {};

assigns the attributes value to attrs if attributes is not undefined and if it is, it assigns a new object to attrs. similiar to:

var attrs;
if(attributes)
   attrs = attributes;
else
  attrs = {};
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
1

The statement:

options || (options = {});

Is a shorthand for:

if(!options) {
    options = {};
}

And it is faster compared to the equivalent shorthand:

options = options || {};
Salman A
  • 262,204
  • 82
  • 430
  • 521