views:

163

answers:

3

I came over a snippet of code the other day that I got curious about, but I'm not really sure what it actually does;

options = options || {};

My thought so far; sets variable options to value options if exists, if not, set to empty object.

Yes/no?

Edit: changed title- thanks, Atomiton

+14  A: 

This is useful to setting default values to function arguments, e.g.:

function test (options) {
  options = options || {};
}

If you call test without arguments, options will be initialized with an empty object.

The Logical OR || operator will return its second operand if the first one is falsy.

Falsy values are: 0, null, undefined, an empty string, NaN, and of course false.

CMS
+5  A: 

Yes, that's exactly what it does.

Jakub Hampl
+6  A: 

Yes. The sample is equivalent to this:

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

The OR operator (||) will short-circuit and return the first truthy value.

jimbojw