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;
}
CodePudding user response:
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.
CodePudding user response:
Yes, both functions do the same thing.