'Do these two snippets return the same value?

I'm not sure how to title this question, but it's concerning a pattern where the || operator is used to resolve a sequence of undefined values to the first defined one.

Are these equivalent?

export function getRuntime(): Runtime {
  return runtime || findWindow() || mockWindow;
}

and

export function getRuntime(): Runtime {
  if (runtime) return runtime;
  if (findWindow()) return findWindow();
  return mockWindow;
}


Solution 1:[1]

Both of the code snippets do the same thing, as the || and return is simply doing the same thing as returning from the if statements.

The only difference between the two is that if findWindow() returns a value which is considered true in JavaScript, it will run twice. This "issue" only occurs in the second one.

Solution 2:[2]

Yes, both functions do the same thing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan M
Solution 2 Jackson Porciúncula