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

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


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.