Question Bank
JavaScript Language Trivia
Difficulty: Easy
Beginner JS quirks to predict and explain: `==` vs `===`, hoisting, `this` binding in different call sites, and one quick closure trace.
JavaScript Language Trivia
Beginner JS quirks to predict and explain: `==` vs `===`, hoisting, `this` binding in different call sites, and one quick closure trace.
1,142 views
23
Predict each line of output and explain why == returns true for some non-identical types while === does not.
Examples
Example 1:
Input: evaluate 0 == '', 0 == '0', '' == '0', null == undefined, null === undefined
Output: true, true, false, true, false
Explanation: == applies abstract equality with coercion toward Number for primitives. 0 == '' becomes 0 == 0. '' and '0' are both strings, no coercion, compared by content. null and undefined are abstract-equal only to each other by spec. === requires same type, so null === undefined is false.What does the snippet print? Explain function vs var vs let / const hoisting in one sentence each.
Examples
Example 1:
Input: console.log(typeof foo); console.log(typeof bar); function foo() {} var bar = 1;
Output: function, then undefined
Explanation: Function declarations are hoisted with their body, so foo is fully defined before line 1. var declarations are hoisted but their assignment stays in place, so bar exists as undefined. let / const stay in TDZ until their declaration line executes.Predict each call's output. Why does the arrow function inside obj.method2 see this differently from the regular function in obj.method1?
Examples
Example 1:
Input: obj.method1() (regular function); obj.method2() (regular function holding an inner arrow); obj.method3() (regular function holding an inner regular function)
Output: 'gizmo', 'gizmo', undefined
Explanation: Regular function this is determined by call site. Arrow functions capture this lexically, so the inner arrow in method2 still sees obj. The inner regular function in method3 is called as a plain function, so its this is undefined in strict mode.What does the loop print, and what is the canonical fix to make it print 0 1 2?
Examples
Example 1:
Input: for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
Output (buggy version): 3 3 3
Output (fixed version with let i): 0 1 2
Explanation: var declares a single function-scoped binding shared across iterations, so the deferred callbacks all observe the final i = 3. let declares a per-iteration block binding, capturing the iteration's value in each closure.