let, var, and const (Difference in Scopes)
In JavaScript, variable declarations are handled using let, var, and const. Each has its own scope rules and use cases, influencing how variables are managed in the code.
Key concepts
var
Function-scoped, can be redeclared, and prone to hoisting issues.
let
Block-scoped, introduced in ES6, safer for modern development.
const
Block-scoped and immutable (cannot be reassigned).
Step by step
Scope:
var is function-scoped:
function example() {
if (true) {
var x = 10;
}
console.log(x); // 10
}let and const are block-scoped:
if (true) {
let x = 10;
const y = 20;
}
console.log(x, y); // ReferenceErrorRedeclaration:
var allows redeclaration; let and const do not:
var x = 1;
var x = 2; // Allowed
let y = 1;
let y = 2; // SyntaxErrorMutability:
const prevents reassignment but does not make objects immutable:
const obj = { name: 'Alice' };
obj.name = 'Bob'; // Allowed
obj = {}; // ErrorExamples
var hoisting issue:
console.log(x); // Undefined
var x = 10;let and const prevent this:
console.log(y); // ReferenceError
let y = 10;Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Rewrite code using var to use let or const.
- Explain the output of code snippets that mix scopes.
Summary
Use let and const for predictable scoping and to follow modern best practices. Avoid var in new codebases.
Read more
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus