Ruby's ||= (or equals) in JavaScript?
Solution 1:
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 :)
Solution 2:
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
Solution 3:
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.
Solution 4:
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.
Solution 5:
Logical nullish assignment (??=)
x ??= 23
Documentation & Browser compatibility