Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 432
Xiphias Avatar asked Nov 08 '13 18:11

Xiphias


People also ask

How do you assign default values to variables?

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.

How can one use the logical or operator to provide fallback values to a variable?

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 .

What is the default value of variable in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.


2 Answers

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!"
like image 159
KooiInc Avatar answered Nov 15 '22 16:11

KooiInc


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!");
like image 32
Andrew Clark Avatar answered Nov 15 '22 15:11

Andrew Clark