Ruby's ||= (or equals) in JavaScript?
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
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.