var vs let vs const
Three Ways to Declare
In JavaScript, there are three keywords used to declare variables: var, let, and const. Understanding the difference between them is a fundamental skill for any modern developer.
1. var (The Old Way)
Before 2015, var was the only way to declare variables.
var language = "JavaScript";
var language = "Python"; // var allows re-declaration without errors!
Verdict: You should generally avoid using var in modern JavaScript because it has confusing rules regarding "scope" (where the variable is available in your code) and allows accidental re-declarations which can cause terrible bugs.
2. let (The Modern Standard)
Introduced in ES6 (2015), let is the modern replacement for var. It allows you to declare a variable whose value can be reassigned later, but it prevents you from accidentally declaring the same variable twice.
let score = 10;
score = 15; // Perfectly fine! Reassigning the value.
// let score = 20; // Error! Cannot re-declare 'score'
3. const (For Constants)
Also introduced in ES6, const stands for "constant". You use it to declare variables whose values should never change.
const PI = 3.14159;
// PI = 3.14; // Error! Cannot reassign a constant.
Note: When using const with Objects and Arrays, you cannot reassign the variable itself, but you can modify the contents inside it!
Best Practice Rule of Thumb:
- Always use
constby default. - If you know the variable's value will need to change later (like a counter in a loop), use
let. - Pretend
vardoesn't exist.
💡 Himanshu's Tip:
When I write code, I use const for exactly 95% of my variables. It prevents accidental bugs where you overwrite data. Only switch it to let when you hit an error telling you that you can't reassign it!
Interview Questions
- What are the main differences between
varandlet? - Why is
constthe recommended default for declaring variables? - Can you modify the contents of an array declared with
const?