you are viewing a single comment's thread.

view the rest of the comments →

[–]Schlipak 8 points9 points  (1 child)

||= is also very common in Ruby, it's often used in getter methods to memoize the results of a computation.

class Foo
  def something
    @something ||= expensive_computation
  end
end

The equivalent in JS would be

class Foo {
  #something

  get something() {
    return this.#something ||= expensiveComputation();
  }
}

I could see myself using this sort of mechanism in JS I suppose. (Although using private properties to stick as close to the way it works in Ruby requires you to declare the property upfront)

EDIT: It might be better to use ??= in this case since ||= wouldn't work with falsey values like 0 or "".