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.