What is the difference between var, let, and const in JavaScript?
Asked on Jul 04, 2024
Answer
In JavaScript, "var", "let", and "const" are used to declare variables, but they differ in terms of scope, hoisting, and mutability. Here's a concise explanation with a code example:
// var: Function-scoped or globally-scoped
var x = 10;
if (true) {
var x = 20; // Same variable, x is overwritten
}
console.log(x); // Outputs: 20
// let: Block-scoped
let y = 10;
if (true) {
let y = 20; // Different variable, scoped to the block
}
console.log(y); // Outputs: 10
// const: Block-scoped, cannot be reassigned
const z = 10;
// z = 20; // Error: Assignment to constant variable
console.log(z); // Outputs: 10
Additional Comment:
✅ Answered with JavaScript best practices.- "var" is function-scoped or globally-scoped and can be redeclared and updated.
- "let" is block-scoped, can be updated but not redeclared within the same scope.
- "const" is block-scoped, cannot be updated or redeclared, and must be initialized at the time of declaration.
- Use "let" and "const" for better block scope management and to avoid issues with variable hoisting.
Recommended Links:
← Back to All Questions