๐จ
JavaScript
Hoisting, this, the event loop, and coercion โ the rules output questions test.
var / let / const
TDZ = accessing a let/const before its line throws ReferenceError.
| Scope | Hoisted | Redeclare | Reassign | |
|---|---|---|---|---|
| var | function | yes โ undefined | yes | yes |
| let | block | yes (TDZ) | no | yes |
| const | block | yes (TDZ) | no | no |
this binding (check in this order)
- new Foo() โ this = the new object
- fn.call/apply/bind(obj) โ this = obj (explicit)
- obj.fn() โ this = obj (implicit)
- plain fn() โ this = undefined (strict) / globalThis (sloppy)
- Arrow fn โ no own this; inherits from enclosing scope
Event loop order
- 1. Run all synchronous code (the current call stack).
- 2. Drain ALL microtasks (Promise .then/catch/finally, queueMicrotask).
- 3. Run ONE macrotask (setTimeout, setInterval, I/O), then repeat from 2.
- So: sync โ microtasks โ one timer โ microtasks โ next timer โฆ
Coercion gotchas
Always use === unless you specifically want loose equality. Falsy: false, 0, "", null, undefined, NaN.
| Expression | Result |
|---|---|
| [] + [] | "" (empty string) |
| [] + {} | "[object Object]" |
| 0 == "" | true (both โ 0) |
| null == undefined | true |
| NaN === NaN | false (use Number.isNaN) |
| typeof null | "object" (historical bug) |
SDE-2 Launchpad ยท JavaScript cheat sheet