Test Yourself!

These twelve questions span the whole chapter and are typical interview material. Treat each numbered snippet as a separate ES module (a .mjs file), write down what it logs, then check your answers.

Questions
Questions 1-11: what does each snippet log?JavaScriptLive
// 1. Closures and loop scope
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j));
// 2. The event loop: in which order do the letters appear?
console.log('A');
setTimeout(() => console.log('B'));
Promise.resolve().then(() => console.log('C'));
(async () => { console.log('D'); await null; console.log('E'); })();
console.log('F');
// 3. What does the last line do?
const counter = { n: 0, inc() { return ++this.n; }, arrow: () => this };
console.log(counter.inc(), counter.arrow());
const { inc } = counter; inc();
// 4. Numbers and types
console.log(0.1 + 0.2 === 0.3, [10, 9, 1].sort(), typeof null, NaN === NaN, Object.is(NaN, NaN));
// 5. Callbacks with extra arguments
console.log(['1', '2', '3'].map(parseInt), ['1', '2', '3'].map(Number));
// 6. Copying objects
const a = { n: 1, inner: { n: 1 } };
const b = { ...a }; b.n = 2; b.inner.n = 2;
console.log(a.n, a.inner.n);
// 7. Defaults and nullish coalescing
const { x = 5, y = 5 } = { x: null, y: undefined };
console.log(x, y, 0 || 'd', 0 ?? 'd', null ?? 'd');
// 8. What survives JSON?
console.log(JSON.stringify({ a: undefined, b() {}, [Symbol('c')]: 1, d: NaN, e: new Date(0) }));
// 9. Two-way generators
function* gen() { const x = yield 1; yield x * 2; }
const g = gen();
console.log(g.next(5).value, g.next(10).value, g.next().done);
// 10. Promise combinators
console.log((await Promise.allSettled([Promise.reject(new Error('x')), 42])).map((r) => r.status));
await Promise.any([Promise.reject(1), Promise.reject(2)])
  .catch((e) => console.log(e.name, e.errors));
// 11. Private fields and brand checks
class Point { #x = 1; static isPoint(o) { return #x in o; } }
console.log(Point.isPoint(new Point()), Point.isPoint({ x: 1 }), typeof Point);

Question 12. Can a == 1 && a == 2 && a == 3 ever be true? One way shows you understand coercion; four or more make you a JavaScript expert.

Answers are in Appendix G.