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!
The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.
The way this works is that in JavaScript, an undefined variable is falsy, meaning that in any boolean comparaison operation, it will evaluate to false . You can then use the OR operator to combine two values and it will return the first value that evaluates to true .
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.
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!"
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!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With