In JavaScript, we declare variables using var, let, or const. While they all store values, they behave differently in terms of scope, hoisting, and mutability.
var – The Old Way
var is the original way to declare variables in JavaScript. It is function-scoped, which means it’s accessible anywhere inside the function it’s declared in. If declared outside of a function, it’s globally scoped.
function example() {
var message = "Hello";
if (true) {
var message = "Hi"; // Same variable!
console.log(message); // "Hi"
}
console.log(message); // "Hi"
}
Note: The variable got overwritten inside the if block. That’s because var doesn’t care about block scope.
let – The Modern and Safer Option
let was introduced in ES6 (2015). It is block-scoped, meaning it’s only accessible within the block where it’s defined.
function example() {
let message = "Hello";
if (true) {
let message = "Hi"; // Different variable!
console.log(message); // "Hi"
}
console.log(message); // "Hello"
}
This makes let much safer and predictable for most use cases.
const – For Constants
const is also block-scoped like let, but it creates a read-only reference to a value. You cannot reassign it.
const name = "Alice";
name = "Bob"; // ❌ Error: Assignment to constant variable
However, const doesn’t make the value itself immutable if it’s an object or array:
const user = { name: "Alice" };
user.name = "Bob"; // ✅ Works!
Hoisting Differences
varis hoisted and initialized asundefined.letandconstare hoisted but not initialized. Accessing them before declaration results in aReferenceError.
console.log(a); // undefined
var a = 10;
console.log(b); // ReferenceError
let b = 20;
When to Use What?
- Use
constby default for values that shouldn’t change. - Use
letwhen you expect the value to change. - Avoid
varin modern code unless working with legacy projects.
Conclusion
Understanding the difference between var, let, and const helps you write cleaner and more predictable JavaScript code. Prefer let and const in modern development, and leave var in the past where it belongs.
Post a Comment