JavaScript Interview Question #5
What is the difference between var, let, and const?
JavaScript Fundamentals, Types, Scope & Functions Junior Beginner
Quick Interview Answer
var is function-scoped, can be redeclared in the same scope, and its declaration is hoisted and initialized with undefined. let and const are block-scoped and cannot be redeclared in the same block.
Detailed Explanation
var is function-scoped, can be redeclared in the same scope, and its declaration is hoisted and initialized with undefined. let and const are block-scoped and cannot be redeclared in the same block.
let allows reassignment, while const prevents reassignment of the variable binding. A const object can still have its properties changed unless the object is separately made immutable. Modern JavaScript generally prefers const by default and let when reassignment is required.
Code Example
function example() {
if (true) {
var x = 1;
let y = 2;
const z = 3;
}
console.log(x); // 1
// console.log(y); // ReferenceError
// console.log(z); // ReferenceError
}