Skip to content Skip to sidebar Skip to footer

Ruby's ||= (or Equals) In Javascript?

I love Ruby's ||= mechanism. If a variable doesn't exist or is nil, then create it and set it equal to something: amount # is nil amount ||= 0 # is 0 amount ||= 5 # is 0 I need to

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:

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

Post a Comment for "Ruby's ||= (or Equals) In Javascript?"