Var vs Let vs Const in JavaScript: Key Differences and Usage
var declares variables with function scope and allows redeclaration, let declares block-scoped variables that can be reassigned but not redeclared in the same scope, and const declares block-scoped variables that cannot be reassigned after initialization.Quick Comparison
Here is a quick table comparing var, let, and const on key factors:
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Hoisting | Yes, initialized as undefined | Yes, but in temporal dead zone | Yes, but in temporal dead zone |
| Reassignment | Allowed | Allowed | Not allowed |
| Redeclaration in same scope | Allowed | Not allowed | Not allowed |
| Use case | Legacy code, function variables | Variables that change value | Constants that never change |
Key Differences
var is function-scoped, meaning it is visible throughout the entire function it is declared in, even before the declaration due to hoisting, where the variable is moved to the top and initialized as undefined. This can cause bugs if you use the variable before assigning a value.
let and const are block-scoped, so they only exist inside the nearest curly braces {}. They are hoisted but not initialized, causing a "temporal dead zone" where accessing them before declaration throws an error.
The main difference between let and const is that let allows you to reassign the variable later, while const does not allow reassignment after the initial value is set. However, objects declared with const can still have their properties changed.
Code Comparison
function testVar() { console.log(x); // undefined due to hoisting var x = 5; x = 10; // reassignment allowed var x = 20; // redeclaration allowed console.log(x); // 20 } testVar();
let and const Equivalent
function testLetConst() { // console.log(y); // ReferenceError: Cannot access 'y' before initialization let y = 5; y = 10; // reassignment allowed // let y = 20; // SyntaxError: Identifier 'y' has already been declared console.log(y); // 10 const z = 15; // z = 20; // TypeError: Assignment to constant variable. console.log(z); // 15 } testLetConst();
When to Use Which
Choose const by default for variables that should not change, which helps prevent bugs and makes your code easier to understand. Use let when you need to reassign a variable, such as counters or values that update. Avoid var in modern code because its function scope and hoisting behavior can cause unexpected bugs; it is mainly kept for legacy support.
Key Takeaways
const is best for values that never change and improves code safety.let is for variables that need reassignment within a block scope.var is function-scoped and allows redeclaration, which can lead to bugs.var in new code; prefer let and const.let or const before declaration causes errors due to temporal dead zone.