Question presented to candidate: "If I write someCondition && doSomethingExpensive(), and someCondition is false, does doSomethingExpensive() actually get called? Walk me through exactly why or why not."
What a strong answer should cover:
- 📌 Interview term: short-circuit evaluation —
&&and||evaluate their left-hand side first, and stop entirely — never evaluating the right-hand side at all — as soon as the overall result is already determined. - 📌 Interview term: the direct, verified answer to the prompt — verified directly with a real call counter:
false && sideEffect()genuinely left the counter at 0 —sideEffect()was never actually called, not just its return value ignored.true && sideEffect()genuinely called it (counter became 1). - 📌 Interview term:
||'s mirrored rule — verified directly:true || sideEffect()genuinely left the counter at 0 (short-circuited on the first truthy value), whilefalse || sideEffect()genuinely called it. - A precise answer names the real, common practical use: a guard pattern like
user && user.name— verified directly, this genuinely avoids a realTypeErrorthatuser.namealone would throw whenuserisnull, because the short-circuit never even attempts to evaluateuser.nameat all. - 📌 Interview term: the classic real pitfall — verified directly:
count || 10used as a "default value" pattern genuinely returns10even whencountis the legitimately valid value0, because0is falsy; the real, correct fix for exactly this case is the nullish coalescing operator??, which verified directly correctly preserved0.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering whether the expensive function call actually happens (with real proof it is skipped entirely, not just its result discarded) is the strong signal.
Code / implementation expected: Yes — a real call-counter proof that the right-hand side is never even invoked is the clearest, most convincing demonstration.