๐ฏ Understanding the differences between var
, let
, and const
is crucial for writing modern JavaScript code. Let's explore how each declaration type works and when to use them.
Variable Declaration Overview
Here's a quick comparison:
var x = 1; // Function-scoped, can be redeclared and updated
let y = 2; // Block-scoped, can be updated but not redeclared
const z = 3; // Block-scoped, cannot be updated or redeclared
Scope Differences
var - Function Scope
function example() {
var x = 1;
if (true) {
var x = 2; // Same variable!
console.log(x); // 2
}
console.log(x); // 2
}
console.log(typeof x); // "undefined" (not accessible outside function)
let and const - Block Scope
function example() {
let x = 1;
const y = 1;
if (true) {
let x = 2; // Different variable
const y = 2; // Different variable
console.log(x, y); // 2, 2
}
console.log(x, y); // 1, 1
}
Hoisting Behavior
var Hoisting
console.log(x); // undefined
var x = 5;
// Is interpreted as:
var x;
console.log(x);
x = 5;
let and const Hoisting
console.log(x); // ReferenceError
let x = 5;
console.log(y); // ReferenceError
const y = 5;
Reassignment Rules
var - Can be Reassigned
var count = 1;
count = 2; // OK
var count = 3; // Also OK (redeclaration)
let - Can be Reassigned but Not Redeclared
let count = 1;
count = 2; // OK
let count = 3; // Error: count has already been declared
const - Cannot be Reassigned
const API_KEY = 'abc123';
API_KEY = 'xyz789'; // Error: Assignment to constant variable
// But object properties can be modified
const user = { name: 'John' };
user.name = 'Jane'; // OK
user = { name: 'Bob' }; // Error: Assignment to constant variable
Best Practices
1. Default to const
// Good practice
const PI = 3.14159;
const BASE_URL = 'https://api.example.com';
const config = {
theme: 'dark',
language: 'en'
};
2. Use let for Variables That Will Change
// Counter example
let count = 0;
for (let i = 0; i < 5; i++) {
count += i;
}
// Accumulator example
let sum = 0;
numbers.forEach(num => {
sum += num;
});
3. Avoid var in Modern Code
// Instead of
var userId = 123;
var userRole = 'admin';
// Use
const userId = 123;
let userRole = 'admin';
Common Use Cases
1. Loop Iterations
// Using let in loops
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Outputs: 0, 1, 2
// Using var (problematic)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Outputs: 3, 3, 3
2. Constants and Configuration
const CONFIG = {
API_URL: 'https://api.example.com',
MAX_RETRIES: 3,
TIMEOUT: 5000
};
const MONTHS = Object.freeze([
'January', 'February', 'March',
// ...
]);
3. Temporary Variables
function processData(data) {
let processed = data;
// Modify processed data
processed = processed.trim();
processed = processed.toLowerCase();
return processed;
}
Real-World Examples
1. API Service
const API_KEY = 'your-api-key';
const BASE_URL = 'https://api.example.com';
let requestCount = 0;
async function fetchData(endpoint) {
const url = `${BASE_URL}${endpoint}`;
let response;
try {
requestCount++;
response = await fetch(url, {
headers: { 'Authorization': API_KEY }
});
} catch (error) {
console.error('API Error:', error);
}
return response;
}
2. Form Handling
const form = document.querySelector('#userForm');
const REQUIRED_FIELDS = ['name', 'email', 'password'];
let isSubmitting = false;
form.addEventListener('submit', async (e) => {
e.preventDefault();
if (isSubmitting) return;
isSubmitting = true;
const formData = new FormData(form);
try {
await submitForm(formData);
} finally {
isSubmitting = false;
}
});
Memory and Performance Considerations
// Memory-efficient
const heavyObject = {
// large object
};
function processData() {
// Use const for references that won't change
const data = heavyObject;
// Use let for values that will change
let processed = 0;
// Process data...
}
Conclusion
Choose your variable declarations wisely:
- Use
const
by default - Use
let
when you need to reassign values - Avoid
var
in modern JavaScript code
Following these guidelines will make your code more predictable, easier to maintain, and less prone to bugs. Remember that using const
doesn't make your objects immutableโit only prevents reassignment of the variable itself.