What is the difference between let, const, and var?
Answer:
1. Scope:
varis function-scoped.letandconstare block-scoped, meaning they are only accessible within the block where they are defined.
2. Redeclaration:
varallows redeclaration of the same variable in the same scope.letandconstdo not allow redeclaration in the same scope.
3. Reassignment:
varandletallow reassignment.constdoes not allow reassignment after initialization.
4. Hoisting:
varis hoisted and initialized asundefined.letandconstare hoisted but remain uninitialized until their declaration is encountered. Accessing them before declaration results in aReferenceError.
Examples
var example
function exampleVar() {
var x = 10;
if (true) {
var x = 20; // Same variable, re-declared
console.log(x); // 20
}
console.log(x); // 20
}
exampleVar();
let example
function exampleLet() {
let x = 10;
if (true) {
let x = 20; // Different variable due to block scope
console.log(x); // 20
}
console.log(x); // 10
}
exampleLet();
const example
function exampleConst() {
const x = 10;
// x = 20; // Error: Assignment to constant variable
console.log(x); // 10
}
exampleConst();
Key Points
- Use let for variables that will be reassigned later.
- Use const for variables that should not change.
- Avoid var in modern JavaScript development due to its function-scoping and hoisting behavior.