Use value if it exists, else assign default using the or operator

Xiphias picture Xiphias · Nov 8, 2013 · Viewed 16.2k times · Source

I found this example in a book:

// Create _callbacks object, unless it already exists
var calls = this._callbacks || (this._callbacks = {});

I simplified it so that I did not have to use a special object scope:

var a = b || (b = "Hello!");

When b is defined, it works. When b is not defined, it does not work and throws a ReferenceError.

ReferenceError: b is not defined

Did I do anything wrong? Thank you!

Answer

Andrew Clark picture Andrew Clark · Nov 8, 2013

When performing a property lookup like this._callback, if the _callbacks property does not exist for this you will get undefined. However if you just do a lookup on a bare name like b, you will get a reference error if b does not exist.

One option here is to use a ternary with the typeof operator, which will return "undefined" if the operand is a variable that has not been defined. For example:

var a = typeof b !== "undefined" ? b : (b = "Hello!");