42

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?

Martin.
  • 10,494
  • 3
  • 42
  • 68
ptrn
  • 4,902
  • 6
  • 28
  • 30

5 Answers5

52

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, the empty string (""), NaN, and of course false.

ES6 UPDATE: Now, we have real default parameter values in the language since ES6.

function test (options = {}) {
  //...
}

If you call the function with no arguments, or if it's called explicitly with the value undefined, the options argument will take the default value. Unlike the || operator example, other falsy values will not cause the use of the default value.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
14

It's the default-pattern..

What you have in your snippet is the most common way to implement the default-pattern, it will return the value of the first operand that yields a true value when converted to boolean.

var some_data   = undefined;
var some_obj_1  = undefined;
var some_obj_2  = {foo: 123};

var str = some_data || "default";
var obj = some_obj1 || some_obj2  || {};

/* str == "default", obj == {foo: 123} */

the above is basically equivalent to doing the following more verbose alternative

var str = undefined;
var obj = undefined;

if (some_data) str = some_data;
else           str = "default";

if      (some_obj1) obj = some_obj1;
else if (some_obj2) obj = some_obj2;
else                obj = {};

examples of values yield by the logical OR operator:

1         || 3         -> 1
0         || 3         -> 3
undefined || 3         -> 3
NaN       || 3         -> 3
""        || "default" -> "default"
undefined || undefined -> undefined
false     || true      -> true
true      || false     -> true
null      || "test"    -> "test"
undefined || {}        -> {}
{}        || true      -> {}

null || false     || {} -> {}
0    || "!!"      || 9  -> "!!"

As you can see, if no match is found the value of the last operand is yield.


When is this useful?

There are several cases, though the most popular one is to set the default value of function arguments, as in the below:

function do_something (some_value) {
  some_value = some_value || "hello world";

  console.log ("saying: " + some_value);
}

...

do_something ("how ya doin'?");
do_something ();

saying: how ya doin'?
saying: hello world

Notes

This is notably one of the differences that javascript have compared to many other popular programming languages.

The operator || doesn't implicitly yield a boolean value but it keeps the operand types and yield the first one that will evaluate to true in a boolean expression.

Many programmers coming from languages where this isn't the case (C, C++, PHP, Python, etc, etc) find this rather confusing at first, and of course there is always the opposite; people coming from javascript (perl, etc) wonders why this feature isn't implemented elsewhere.

Community
  • 1
  • 1
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
  • oh yeah, stupid typo - will fix it asap (**edit**: fixed). I originally wrote this answer to a question which was flagged as duplicate of this one, after checking the answers in this thread I thought that my answer was a bit better than the others and therefore I posted it here. – Filip Roséen - refp Jul 19 '12 at 11:27
  • Good stuff. The comparison table was neat, so still appreciated :) – ptrn Jul 19 '12 at 13:11
10

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.

jimbo
  • 11,004
  • 6
  • 29
  • 46
6

Yes, that's exactly what it does.

Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
4

Found another variation of this:

options || (options = {});

Seems to do the same trick.

Oleg
  • 74
  • 1
  • 7
  • 2
    The Boolean evaluation will occur in both versions, but in this version, variable assignment doesn't have to occur every time, which saves CPU (granted the gain is minuscule). Then again, I don't know if the interpreter will have to parse the parens, negating the gain? Can you drop the parens? – skibulk Mar 10 '14 at 15:48
  • 1
    @skibulk can't probably drop the parens as equals has lower precedence than the logic operators, but why should they have to parse? and if you speak of the usual parsing that it is probably nothing – yoel halb Nov 09 '14 at 01:56