This file covers the foundation that explains most JavaScript interview questions: compilation, scope, and hoisting.
JavaScript is compiled just in time, scope is lexical, and hoisting is the result of declarations being processed before execution.
- JavaScript is not simply executed line by line with no preparation.
- The engine parses and compiles code before execution.
- This explains scope registration and hoisting behavior.
JavaScript is compiled just in time. The engine first parses and registers declarations, then executes the code. That is why variables and functions can appear to exist before the line where they are written.
Scope is determined by where code is written, not where it is called from.
- Functions and blocks create scope.
- Lookups start in the current scope and move outward.
- Inner scope can read outer scope, but outer scope cannot read inner scope.
function outer() {
const a = 1;
function inner() {
const b = 2;
console.log(a + b);
}
inner();
}- Confusing lexical scope with dynamic scope.
- Thinking scope depends on who called the function.
LHS means assignment target. RHS means value retrieval.
let a;
a = 2; // LHS lookup for a
console.log(a); // RHS lookup for aThis helps explain why some failures become ReferenceError and why assignment and reading are treated differently by the engine.
Hoisting is not code movement. It is the visible result of declaration processing during compilation.
- Function declarations are hoisted with their definitions.
vardeclarations are hoisted and initialized toundefined.letandconstare hoisted too, but stay in the temporal dead zone until initialized.
console.log(a); // undefined
var a = 2;sayHi();
function sayHi() {
console.log("hi");
}- Saying
letandconstare not hoisted at all. - Confusing hoisting with initialization.
A let or const binding exists from the start of scope but cannot be accessed before initialization.
console.log(count); // ReferenceError
let count = 1;They test whether you understand that JavaScript prefers static lexical analysis.
evalandwithmake scope reasoning harder.- They hurt optimization and readability.
- They should generally be avoided.
Scope determined by where code is written.
The observable result of declarations being processed before execution.
var is function-scoped and initialized to undefined; let is block-scoped and has a temporal dead zone.
Because it explains execution order, access rules, and many common bugs.