SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 30
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 30 of 30

Tricky output questions (interview round)

== vs ===typeof nullNaNhoisting and the TDZ[] + {}0.1 + 0.2var in loopsthis in callbacks

These are the notes for JavaScript Coding Questions, episode 30, the last episode of the series: interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode we built an event emitter and a store with expiring keys, and tested them with node:test. Today is the round everybody fears: "what does this print?" Every surprise comes from one rule, and we find each rule through a real bug.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real.

How to answer an output question

  1. Read every line slowly. What type is each value? Number, string, boolean, null, undefined, object, array, function?
  2. Name the rule: type conversion, hoisting, scope, floating point, or this.
  3. Say the answer and the reason out loud. The interviewer scores the reason.
  4. When practising, run it and check the output matches your reason, not just your guess.

Type conversion (also called coercion) is JavaScript changing a value's type automatically, like turning the string "5" into the number 5. Most "tricky" outputs are conversions you didn't ask for.

Round 1: == vs ===

The bug: a zero score marked absent

A result page: an empty marks box means absent; 35 or more is pass; anything else is fail. Ravi sat the exam and scored 0.

function result(marks) {
  if (marks == "") return "absent";
  return marks >= 35 ? "pass" : "fail";
}
console.log(result(72), result(""), result(0));
pass absent absent

Why? == (loose equality) compares values of different types by converting them first. "" converts to the number 0, so 0 == "" is true.

=== (strict equality) never converts: different types are simply not equal.

function result(marks) {
  if (marks === "") return "absent";
  return marks >= 35 ? "pass" : "fail";
}
console.log(result(72), result(""), result(0));
pass absent fail

Real life. A relaxed ticket checker accepts a photo of a ticket ("close enough"): that's ==. A strict one wants the real ticket, of the right kind: ===. Use === (and !==) by default.

The == rules in one table

Comparison Result Why
0 == "0" true "0" → 0
0 == "" true "" → 0
"" == "0" false both strings: no conversion, different text
null == undefined true a special rule: they equal each other and nothing else
null == 0 false null only == undefined
[] == false true [] → "" → 0, false → 0
NaN == NaN false NaN equals nothing, not even itself

The rough algorithm of ==: same type → compare like ===. null/undefined → equal only to each other. Otherwise turn booleans into numbers, objects into primitives (via toString/valueOf), and compare string vs number as numbers.

console.log(0 == "0", 0 == "", "" == "0");
console.log(null == undefined, null === undefined, null == 0);
console.log(typeof null, typeof NaN, typeof [], typeof function () {});
console.log(NaN === NaN, Number.isNaN(NaN), [NaN].includes(NaN), [NaN].indexOf(NaN));
true true false
true false false
object number object function
false true true -1
  • 0 == "0" and 0 == "" are both true, but "" == "0" is false: == isn't even transitive (a = b and a = c don't mean b = c).
  • typeof null is "object"; typeof NaN is "number"; arrays are objects (use Array.isArray); functions have their own "function".
  • NaN ("Not a Number") is the result of a failed maths operation, like "abc" * 15. It is the only value not equal to itself. Test it with Number.isNaN(x). includes uses a comparison that treats NaN as equal (SameValueZero), but indexOf uses ===, so it can't find NaN.

typeof null crashes a real check

function showName(user) {
  if (typeof user === "object") return user.name;
  return "guest";
}
console.log(showName({ name: "Asha" }));
console.log(showName(undefined));
console.log(showName(null));
Asha
guest
main.js:2
  if (typeof user === "object") return user.name;
                                            ^

TypeError: Cannot read properties of null (reading 'name')

Why? typeof null === "object" is a bug from the very first version of JavaScript (1995). Fixing it would break old websites, so it stays. null passes the check, and null has no properties.

function showName(user) {
  if (typeof user === "object" && user !== null) return user.name;
  return "guest";
}
console.log(showName({ name: "Asha" }));
console.log(showName(undefined));
console.log(showName(null));
const nobody = null;
console.log(nobody?.name ?? "guest");
Asha
guest
guest
guest
  • Optional chaining a?.b gives undefined instead of throwing when a is null or undefined.
  • Nullish coalescing a ?? b gives b only when a is null or undefined (unlike ||, which also replaces 0 and "").
const marks = 0;
console.log(marks || "not entered", marks ?? "not entered");
console.log("abc" * 15, Number.isNaN("abc" * 15), isNaN("abc"), Number.isNaN("abc"));
not entered 0
NaN true true false

The old global isNaN("abc") converts first ("abc" → NaN) and says true; Number.isNaN("abc") doesn't convert: a string is not NaN, so false.

Round 2: hoisting and the temporal dead zone (TDZ)

Before running any line of a scope (a function, a block, the file), JavaScript first reads every declaration in it. This is called hoisting.

Declared with Before its line you get Scope
function f() {} the whole function, ready to call function
var x x exists, value undefined function
let x / const x ReferenceError (the TDZ) block { }
class C {} ReferenceError (the TDZ) block
const f = () => {} ReferenceError (it's a const) block

The temporal dead zone is the stretch of a scope from its start until the let/const line runs: the name exists, but using it throws.

Real life. The class register filled in before the bell: a function is a student already in the room; a var is a seat with nobody in it (undefined); a let is a reserved seat behind a locked door.

console.log(greet("Asha"));
function greet(name) { return "Hello " + name; }

console.log(token);
var token = 7;

console.log(counter);
let counter = 1;
Hello Asha
undefined
main.js:7
console.log(counter);
            ^

ReferenceError: Cannot access 'counter' before initialization

That error is a feature: undefined silently hides the mistake; the TDZ shows it.

try { sayBye(); } catch (e) { console.log(e.name + ":", e.message); }
const sayBye = () => "bye";
try { new Ticket(); } catch (e) { console.log(e.name + ":", e.message); }
class Ticket {}
let x = "outer";
{
  try { console.log(x); } catch (e) { console.log(e.name + ":", e.message); }
  let x = "inner"; // this block's own x: the outer one is hidden for the whole block
}
ReferenceError: Cannot access 'sayBye' before initialization
ReferenceError: Cannot access 'Ticket' before initialization
ReferenceError: Cannot access 'x' before initialization

The last one surprises people: inside the block, x already means the block's own let x (hoisted), which is still in its TDZ, so the outer x can't be reached.

var in a loop: the clinic calls token 4

A clinic's screen should call tokens 1, 2 and 3, a hundred milliseconds apart.

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log("Calling token", i), 100 * i);
}
Calling token 4
Calling token 4
Calling token 4

Why? var is function-scoped: there is one i for the whole loop. The timeouts run after the loop has finished, and by then the shared i is 4, the value that ended the loop (4 <= 3 is false).

Real life. var is one display board the nurse reads later: it shows 4 by then. let is a printed slip for each patient.

for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log("Calling token", i), 100 * i);
}
Calling token 1
Calling token 2
Calling token 3

With let, a for loop creates a new binding of i for every turn, and each arrow function closes over its own i (a closure: a function remembering the variables around it where it was created, from episode 19). Before let existed (2015), people wrote an IIFE (a function called immediately) to make a new scope each turn:

for (var i = 1; i <= 3; i++) {
  (function (n) {
    setTimeout(() => console.log("old fix, token", n), 10 * n);
  })(i);
}
old fix, token 1
old fix, token 2
old fix, token 3

Round 3a: + with strings and objects

The bug: a ₹12,040 bill

A food app adds a delivery fee from an input box to a ₹120 subtotal. Input boxes always give strings.

const subtotal = 120;
const delivery = "40"; // read from an input box: always a string
console.log("total:", subtotal + delivery);
console.log("after ₹10 off:", subtotal + delivery - 10);
total: 12040
after ₹10 off: 12030

Why? + does two jobs: adding numbers and joining strings (concatenation). If either side is a string (after objects are turned into primitives), + joins. -, *, / and % only do maths, so they convert strings to numbers: "12040" - 10 is 12030.

const subtotal = 120;
const delivery = Number("40"); // turn the text into a number first
console.log("total:", subtotal + delivery);
console.log("after ₹10 off:", subtotal + delivery - 10);

console.log("[] + {}      →", [] + {});
console.log("[] + []      →", JSON.stringify([] + []));
console.log("[1, 2] + [3] →", [1, 2] + [3]);
console.log('1 + "2"      →', 1 + "2");
console.log('"3" * "4"    →', "3" * "4");
total: 160
after ₹10 off: 150
[] + {}      → [object Object]
[] + []      → ""
[1, 2] + [3] → 1,23
1 + "2"      → 12
"3" * "4"    → 12
  • An object in + is first turned into a primitive: an array becomes its items joined with commas ([] → "", [1, 2] → "1,2"), a plain object becomes "[object Object]".
  • So [] + {} is "" + "[object Object]", and [1, 2] + [3] is "1,2" + "3" = "1,23".
  • JSON.stringify shows a string with its quotes, so the empty string is visible.

More conversions to know:

console.log(Number(""), Number(" 42 "), Number("4O"), Number(null), Number(undefined), Number(true));
console.log(parseInt("42px"), parseInt("px42"), parseFloat("3.5kg"), +"7");
console.log(true + true, "5" - "2", "5" + - "2", [] * 2, [5] * 2);
0 42 NaN 0 NaN 1
42 NaN 3.5 7
2 3 5-2 0 10

Number("4O") (letter O) is NaN: Number needs the whole string to be a number; parseInt reads digits until the first non-digit. Unary + converts like Number.

Round 3b: 0.1 + 0.2

const tea = 0.1, sugar = 0.2;
const total = tea + sugar;
console.log(total);
console.log(total === 0.3 ? "bill OK" : "bill mismatch!");
0.30000000000000004
bill mismatch!

Why? JavaScript numbers are 64-bit floating point (IEEE 754 doubles), stored in binary. Just as 1/3 never ends in decimal (0.3333…), 0.1 never ends in binary (0.000110011001100…), so it's cut off to fit. The tiny leftover errors add up. This happens in every language that uses doubles (Python, Java, C).

const tea = 0.1, sugar = 0.2;
const total = tea + sugar;
console.log(Math.abs(total - 0.3) < Number.EPSILON, total.toFixed(2));

const teaPaise = 10, sugarPaise = 20; // whole numbers are exact
console.log(teaPaise + sugarPaise === 30, (teaPaise + sugarPaise) / 100);

console.log(0.1 + 0.7, 1.1 * 3, 0.5 + 0.25);
true 0.30
true 0.3
0.7999999999999999 3.3000000000000003 0.75
  • Compare with a tolerance: Math.abs(a - b) < Number.EPSILON (Number.EPSILON is about 2.2 × 10⁻¹⁶, the gap between 1 and the next double). For bigger values use a tolerance that fits your data, like 1e-9.
  • Round for display with toFixed(2); note it returns a string.
  • For money, count whole paise (integers): whole numbers up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991) are exact.
  • 0.5 and 0.25 are a half and a quarter, which are exact in binary, so 0.5 + 0.25 === 0.75.
console.log(Number.MAX_SAFE_INTEGER, 9007199254740992 === 9007199254740993);
console.log((1.005).toFixed(2), Math.round(1.005 * 100) / 100);
9007199254740991 true
1.00 1

Even rounding can surprise: 1.005 is stored as 1.00499999…, so it rounds down. Another reason to keep money in paise.

Round 3c: this in callbacks

The rule. For a normal function, this is the object the function was called on, decided at call time: t.count() → this is t. Called on its own, count() → this is undefined (in strict mode, which all class code and ES modules use; in old sloppy scripts it falls back to the global object). Arrow functions have no this of their own; they use the this of the code around them.

The bug: a vote tally

class Tally {
  constructor() { this.yes = 0; }
  count(votes) {
    votes.forEach(function (v) {
      if (v === "yes") this.yes++;
    });
    return this.yes;
  }
}
console.log(new Tally().count(["yes", "no", "yes"]));
main.js:5
      if (v === "yes") this.yes++;
                       ^

TypeError: Cannot read properties of undefined (reading 'yes')

Why? forEach calls our callback as a plain function, not on any object. Class bodies are strict mode, so this is undefined.

Fix 1: an arrow function (and a new trap)

class Tally {
  constructor() { this.yes = 0; }
  count(votes) {
    votes.forEach((v) => {
      if (v === "yes") this.yes++;
    });
    return this.yes;
  }
}
const t = new Tally();
console.log(t.count(["yes", "no", "yes"]));
const count = t.count;
console.log(count(["yes"]));
2
main.js:5
      if (v === "yes") this.yes++;
                       ^

TypeError: Cannot read properties of undefined (reading 'yes')

The arrow borrowed count's this. But copying the method into a variable and calling it on its own (a detached method) leaves count's own this undefined. This is exactly what happens with setTimeout(t.count, 100) or button.addEventListener("click", t.count).

Fix 2: bind

class Tally {
  constructor() { this.yes = 0; }
  count(votes) {
    votes.forEach((v) => {
      if (v === "yes") this.yes++;
    });
    return this.yes;
  }
}
const t = new Tally();
console.log(t.count(["yes", "no", "yes"]));
const count = t.count.bind(t);
console.log(count(["yes"]));
2
3

fn.bind(obj) returns a new function whose this is always obj. Other options: a wrapper arrow (setTimeout(() => t.count(list), 100)), or a class field arrow (count = (votes) => { ... }), which is created per object with this fixed.

this in one table

"use strict";
const shop = {
  name: "Chai Point",
  normal() { return this?.name; },
  arrow: () => typeof this,
  later() { return [1].map(function () { return this; }, this)[0].name; },
};
const detached = shop.normal;
console.log(shop.normal(), detached(), shop.arrow(), shop.later());
console.log(shop.normal.call({ name: "Samosa Corner" }), shop.normal.bind({ name: "Idli House" })());
Chai Point undefined object Chai Point
Samosa Corner Idli House
Call this
shop.normal() shop (the object before the dot)
detached() undefined (strict)
an arrow function the this around it (at the top of a CommonJS file it's module.exports, an object)
arr.map(fn, thisArg) thisArg (many array methods take one)
fn.call(obj) / fn.apply(obj) obj, for that one call
fn.bind(obj)() obj, always
new C() the new object

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
== with an empty string marks == "" for 0 absent "" converts to 0 ===
Trusting typeof x === "object" showName(null) TypeError: Cannot read properties of null (reading 'name') typeof null is "object" && x !== null, or x?.name
x === NaN NaN === NaN false NaN equals nothing Number.isNaN(x)
|| for a default 0 || "not entered" not entered 0 is falsy ??
Using let before its line console.log(counter); let counter = 1; ReferenceError: Cannot access 'counter' before initialization the TDZ declare first
var in a loop with callbacks for (var i ...) setTimeout(...) Calling token 4 ×3 one shared i let i
+ with input text 120 + "40" 12040 + joins strings Number(...) first
=== on decimals 0.1 + 0.2 === 0.3 false binary rounding paise, or Math.abs(a - b) < Number.EPSILON
A plain function callback using this forEach(function () { this.yes++ }) TypeError: Cannot read properties of undefined (reading 'yes') a plain call: this is undefined an arrow function
Passing a method as a callback const count = t.count; count([...]) the same TypeError detached from t t.count.bind(t) or () => t.count(...)

Mini project: a "predict the output" drill

A tiny program that runs puzzles and checks your guesses. Fill in guess for each puzzle, run it, and see your score.

const puzzles = [
  { code: '0 == ""', run: () => 0 == "", guess: true },
  { code: "typeof null", run: () => typeof null, guess: "object" },
  { code: "NaN === NaN", run: () => NaN === NaN, guess: true },
  { code: '120 + "40"', run: () => 120 + "40", guess: 160 },
  { code: "0.1 + 0.2 === 0.3", run: () => 0.1 + 0.2 === 0.3, guess: false },
  { code: "[] + {}", run: () => [] + {}, guess: "[object Object]" },
];
let score = 0;
for (const p of puzzles) {
  const actual = p.run();
  const ok = Object.is(actual, p.guess);
  if (ok) score++;
  console.log(`${ok ? "✔" : "✖"} ${p.code.padEnd(18)} → ${JSON.stringify(actual)}${ok ? "" : `  (you said ${JSON.stringify(p.guess)})`}`);
}
console.log(`score: ${score}/${puzzles.length}`);
✔ 0 == ""            → true
✔ typeof null        → "object"
✖ NaN === NaN        → false  (you said true)
✖ 120 + "40"         → "12040"  (you said 160)
✔ 0.1 + 0.2 === 0.3  → false
✔ [] + {}            → "[object Object]"
score: 4/6

Object.is(a, b) is like === but also says Object.is(NaN, NaN) is true, so it can check a NaN guess. padEnd(18) pads the text with spaces to line the arrows up.

Your turn: predict all five (solution)

console.log(typeof undefined, typeof typeof 1);
console.log(null + 1, undefined + 1, "" + null);
console.log([10, 1, 2].sort(), Math.max());
console.log(1 < 2 < 3, 3 > 2 > 1);
undefined string
1 NaN null
[ 1, 10, 2 ] -Infinity
true false
  • typeof undefined is "undefined". typeof 1 is the string "number", and typeof of any string is "string".
  • null + 1: null converts to 0 → 1. undefined + 1: undefined converts to NaN → NaN. "" + null: a string side means join → "null" (console.log shows it as null).
  • [10, 1, 2].sort() compares as text: "1" < "10" < "2" → [1, 10, 2] (episode 28's trap). Math.max() with nothing returns -Infinity, the starting value it compares against.
  • 1 < 2 < 3 is (1 < 2) < 3 = true < 3 = 1 < 3 = true. 3 > 2 > 1 is (3 > 2) > 1 = true > 1 = 1 > 1 = false.

Practice questions (with solutions)

1. What does this print, and why?

console.log([1, 2, 3] == "1,2,3", [] == ![], "b" + "a" + +"a" + "a");
Solution
true true baNaNa
  • [1, 2, 3] == "1,2,3": the array becomes the string "1,2,3" → true.
  • [] == ![]: ![] is false (an object is truthy), then [] == false → 0 == 0 → true.
  • "b" + "a" + +"a" + "a": +"a" is NaN, joined as text → "baNaNa".

2. Fix the loop so it prints 0 1 2 without changing var to let.

var fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map(f => f()).join(" "));
Solution
var fns = [];
for (var i = 0; i < 3; i++) fns.push(((n) => () => n)(i));
console.log(fns.map(f => f()).join(" "));
0 1 2

The outer arrow is called immediately with the current i, and the inner arrow closes over that call's own n. (The original prints 3 3 3.)

3. What does this print?

function f() { return typeof g; var g = 1; function g() {} }
function h() { "use strict"; return this; }
console.log(f(), h(), typeof h.call(5));
Solution
function undefined number

Inside f, the function declaration g is hoisted (and the return runs before var g = 1 assigns), so typeof g is "function". In strict mode a plain call gives this === undefined, and call(5) passes the number 5 as this without wrapping it, so typeof is "number".

4. Make sum exact for money. sum([0.1, 0.2, 0.3]) should be exactly 0.6.

Solution
const sumRupees = list => list.reduce((a, b) => a + b, 0);
const sumPaise = list => list.map(r => Math.round(r * 100)).reduce((a, b) => a + b, 0) / 100;
console.log(sumRupees([0.1, 0.2, 0.3]), sumPaise([0.1, 0.2, 0.3]), sumPaise([0.1, 0.2, 0.3]) === 0.6);
0.6000000000000001 0.6 true

Convert each rupee value to whole paise once (Math.round removes the tiny binary error), add integers exactly, divide at the end.

5. What does this print? (event loop recap from episode 23)

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
Solution
A
D
C
B

Synchronous code first (A, D), then the microtask queue (promise callbacks: C), then timers (B), even with a 0 ms delay.

Quick quiz

console.log([] == false, !![]);
console.log("5" - 2, "5" + 2);
Answer
true true
3 52

A. [] == false: both become numbers ([] → "" → 0, false → 0) → true. !![] is true: every object, even an empty array, is truthy. "5" - 2 does maths (3); "5" + 2 joins ("52").

Interview questions

  1. == vs ===? == converts types before comparing; === compares type and value with no conversion. Prefer ===; x == null (true for null and undefined) is the one common, deliberate use of ==.
  2. Why is typeof null "object"? A bug from JavaScript's first version, kept for compatibility. Check x === null explicitly.
  3. How do you check for NaN? Number.isNaN(x), or Object.is(x, NaN). Never x === NaN.
  4. What is hoisting? What is the TDZ? Declarations are processed before code runs. Functions are ready, var is undefined, let/const/class throw a ReferenceError until their line: the temporal dead zone.
  5. Why does var in a loop with setTimeout print the last value? One function-scoped variable shared by every callback; let creates a new binding per iteration.
  6. Why is 0.1 + 0.2 !== 0.3? Binary floating point can't store 0.1 exactly. Compare with a tolerance, or use integers (paise) for money.
  7. What decides this? How a function is called: on an object, plainly, with call/apply/bind, or with new. Arrow functions take this from where they're written.
  8. [] + {} vs {} + [] at the start of a line? [] + {} is "[object Object]". Typed at the start of a line in a console, {} can be read as an empty block, so {} + [] becomes +[] = 0. Inside an expression (console.log({} + [])) it's "[object Object]".

Glossary

Term Meaning Example
Type conversion (coercion) JavaScript changing a value's type automatically "5" - 2 → 3
Loose equality == Compares after converting types 0 == "" → true
Strict equality === Compares type and value, no conversion 0 === "" → false
Transitive If a = b and b = c then a = c (== doesn't guarantee it) "" == 0, 0 == "0", "" != "0"
typeof An operator giving a value's type as a string typeof 1 → "number"
null / undefined "Deliberately empty" / "not set yet" let x; → undefined
NaN "Not a Number": the result of failed maths; not equal to itself "abc" * 15
Number.isNaN True only for the NaN value, no conversion Number.isNaN(NaN)
Optional chaining ?. Stops at null/undefined and gives undefined user?.name
Nullish coalescing ?? Right side only for null/undefined 0 ?? 5 → 0
Truthy / falsy Values that act as true / false in a condition; falsy: false, 0, "", null, undefined, NaN !![] → true
Hoisting Declarations are read before any code in the scope runs greet() before function greet
Temporal dead zone (TDZ) From the start of a scope until a let/const/class line runs ReferenceError: Cannot access ... before initialization
Function scope / block scope var lives in the whole function; let/const in the nearest { } for (let i ...)
Binding The connection between a name and its value a new i per loop turn
Closure A function that remembers the variables around it each timeout's own i
IIFE A function expression called immediately (function (n) { ... })(i)
Concatenation Joining strings with + "12" + "0"
Primitive A non-object value: number, string, boolean, null, undefined, bigint, symbol [] → "" in +
Floating point (IEEE 754 double) How JavaScript stores numbers: 64 bits, binary 0.1 + 0.2
Number.EPSILON About 2.2e-16, the gap between 1 and the next double a comparison tolerance
Number.MAX_SAFE_INTEGER The largest integer stored exactly (2^53 − 1) 9007199254740991
this The object a normal function was called on, decided at call time t.count() → t
Strict mode Stricter rules (classes and modules use it); plain calls get this === undefined "use strict";
Detached method A method called without its object const f = t.count; f()
bind / call / apply Fix this forever / for one call / for one call with an array of arguments t.count.bind(t)
Object.is Like ===, but NaN equals NaN and +0 differs from -0 Object.is(NaN, NaN)

Summary

  • == converts types; use ===. typeof null is "object": check !== null or use ?.. NaN equals nothing: Number.isNaN.
  • Hoisting: functions ready, var = undefined, let/const/class in the TDZ until their line.
  • var in a loop shares one variable; let gives each turn its own.
  • + with a string joins; -, *, / convert to numbers; objects become strings first ([] + {} → "[object Object]").
  • 0.1 + 0.2 !== 0.3: binary floating point. Count money in whole paise, or compare with a tolerance.
  • this is decided by how a function is called. Arrow functions borrow it; bind fixes it.
  • That's the end of JavaScript Coding Questions: 30 episodes, 90 questions. Redo any episode's questions without watching, and keep practising in the SyntaxPilot compiler. Good luck in your interviews!