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?
JavaScript
x
4
1
export function getRuntime(): Runtime {
2
return runtime || findWindow() || mockWindow;
3
}
4
and
JavaScript
1
6
1
export function getRuntime(): Runtime {
2
if (runtime) return runtime;
3
if (findWindow()) return findWindow();
4
return mockWindow;
5
}
6
Advertisement
Answer
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.