| Tutorials | JavaScript |
Difference Between var, let, and const in JavaScript
In JavaScript, there are three main ways to declare variables: var, let, and const.
Although they may look similar, they have important differences.
var
- Old declaration style (before ES6).
- Has function scope and does not respect block
{ }scope.
var x = 10;
if (true) {
var x = 20;
}
console.log(x); // 20
let
- Introduced in ES6.
- Respects block scope
{ }.
let y = 10;
if (true) {
let y = 20;
console.log(y); // 20
}
console.log(y); // 10
const
- Similar to
letbut the value cannot be reassigned.
const PI = 3.1416;
// PI = 3; ❌ Error
Use let for variables that may change and const for values that should not be modified.