Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's ||= (or equals) in JavaScript?

People also ask

Is it += or =+ in JavaScript?

What does += mean in JavaScript? The JavaScript += operator takes the values from the right of the operator and adds it to the variable on the left. This is a very concise method to add two values and assign the result to a variable hence it is called the addition assignment operator.

What does || in Ruby mean?

a ||= b is a conditional assignment operator. It means: if a is undefined or falsey, then evaluate b and set a to the result. Otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.

Does JavaScript have an equals method?

There are four equality algorithms in JavaScript: IsLooselyEqual ( == ) IsStrictlyEqual ( === ): used by Array.

What does || stand for in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values.


Both are absolutely correct, but if you are looking for something that works like ||= in ruby. The first method which is variable = variable || {} is the one you are looking for :)


You can use the logical OR operator || which evaluates its right operand if lVal is a falsy value.

Falsy values include e.g null, false, 0, "", undefined, NaN

x = x || 1

The operator you asked about has been proposed as a feature in JavaScript. It is currently at Stage 4, and it will be introduced in the next ECMAScript standard, which is expected to be published in 2021.

You can use it now using the plugin-proposal-logical-assignment-operators Babel plugin. I have never used that plugin, so I have no idea how well it works.


If you're working with objects, you can use destructuring (since ES6) like so:

({ myLib: window.myLib = {} } = window);

...but you don't gain anything over the accepted answer except confusion.


Logical nullish assignment (??=)

x ??= 23

Documentation & Browser compatibility