QJavaScript · Interview preparation
How do var, let, and const differ?
The important differences are scope, redeclaration, temporal dead zone behavior, and reassignment.
The idea to remember.
var is function-scoped and can be redeclared in the same scope. let and const are block-scoped and are unavailable before their declaration is initialized because of the temporal dead zone. let allows reassignment; const prevents rebinding, although the contents of an object referenced by a const can still be mutated.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: closure remembers a binding
01 / BEGINNERThe returned function can still use a variable from its outer scope.
function createCounter() {
let count = 0;
return () => ++count;
}
const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2Intermediate: block scope
02 / INTERMEDIATEEach iteration can keep its own binding with let.
const callbacks = [];
for (let i = 0; i < 3; i++) callbacks.push(() => i);
console.log(callbacks.map(fn => fn())); // [0, 1, 2]Real scenario: isolate private state
03 / REAL SCENARIOA factory can retain private data without exposing it globally.
function createCart() {
const items = [];
return {
add: item => items.push(item),
total: () => items.reduce((sum, item) => sum + item.price, 0)
};
}02Check your understanding
Try it in your own words.
Explain how do var, let, and const differ without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse JavaScript study guides ↗