ES6, or ECMAScript 2015, introduced major improvements to JavaScript—including better ways to declare variables. Before ES6, developers used var to declare all variables. But var has some issues, especially with scope. To solve this, ES6 introduced two new keywords: let and const.
1. var – The Old Way
Before ES6, var was the only way to declare variables in JavaScript.
var name = "Kirti";
Problems with var:
- Function Scope Only: It ignores block scope (like inside
{}). - Hoisting:
vardeclarations are moved to the top of the function. This can cause unexpected behavior.
Example:
console.log(x); // undefined
var x = 5;
This doesn’t give an error because JavaScript hoists the var x; declaration to the top.
2. let – Block-Scoped Variable
let is the modern way to declare variables that can change later.
let age = 25;
age = 26; // Allowed
Key Features of let:
- Block Scope: Works only within the block
{}where it is defined. - Not Hoisted like
var: If used before declaration, it gives an error. - Can be updated: You can change the value later.
Example:
{
let city = "Mumbai";
console.log(city); // Mumbai
}
console.log(city); // Error: city is not defined
3. const – For Constants
Use const when you want to declare a variable that cannot be reassigned.
const country = "India";
country = "USA"; // Error
Key Features of const:
- Block Scoped
- Must be initialized at the time of declaration
- Cannot be reassigned
- Does NOT mean immutable if it’s an object or array
Example with object:
const person = { name: "Kirti" };
person.name = "Bhoomi"; // Allowed (changing property, not the object itself)
Differences Between var, let, and const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Reassignment | Yes | Yes | No |
| Hoisting | Yes (undefined) | No (error) | No (error) |
| Use in Loops | Unsafe | Safe | (with care) |
When to Use What?
- Use
letwhen the value needs to change. - Use
constwhen the value should not change. - Avoid
varunless you’re maintaining old code.
Example in Real Code:
function greetUser(isLoggedIn) {
if (isLoggedIn) {
let greeting = "Welcome back!";
console.log(greeting); // No Error
}
// console.log(greeting); // Error: greeting is block-scoped
}
Conclusion
ES6 variables—let and const—give you better control over your code. They are safer, cleaner, and easier to understand than var. By using let for changing values and const for constants, your JavaScript code becomes more modern and bug-free.