let and const
Modern JavaScript provides let and const for declaring variables with block scope.
What are let and const?
In modern JavaScript, let and const are used to declare variables.
Both are block-scoped, but they are different in how their values can be changed.
Simple Definition
let is used when a variable's value may change, while const is used when the variable should not be reassigned.
Difference between let and const in JavaScript
let vs const
| Feature | let | const |
|---|---|---|
| Block Scoped | Yes | Yes |
| Reassignment | Allowed | Not Allowed |
| Redeclaration in Same Scope | No | No |
| Must Initialize | No | Yes |
Example 1: Using let
A let variable can be reassigned after it has been declared.
let age = 20;
age = 21;
console.log("Age:", age);
Example 2: Using const
A const variable must be initialized when it is declared and cannot be reassigned.
const course = "JavaScript";
console.log("Course:", course);
Example 3: Changing a let Variable
let marks = 70;
console.log("Before:", marks);
marks = 85;
console.log("After:", marks);
After: 85
Example 4: Block Scope
Variables declared using let and const are available only inside their block.
{
let city = "Pune";
const country = "India";
console.log("City:", city);
console.log("Country:", country);
}
Country: India
Example 5: let and const Together
let student = "Amit";
const course = "JavaScript";
student = "Rahul";
console.log("Student:", student);
console.log("Course:", course);
Course: JavaScript
Important Note
Use let when you know that the variable value needs to change.
Use const by default when the variable should not be reassigned.
Summary
let and const are modern JavaScript variable declarations. Both are block-scoped. The main difference is that let can be reassigned while const cannot be reassigned.