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!
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!
Share Improve this question asked Nov 8, 2013 at 18:22 XiphiasXiphias 4,7165 gold badges30 silver badges52 bronze badges2 Answers
Reset to default 11When 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!");
It should work in this form:
var b, a = b || (b = "Hello!", b);
// ^ assign b
// ^ () and , for continuation
// ^ return the new value of b
//=> result: a === b = "Hello!"