Variable Declarations with let and const
🎯 Introduction
This article explains how ES6's let and const differ from var. You will learn when to use each declaration, how scope and hoisting affect them, and whether objects declared with const can change. These fundamentals help you avoid common mistakes and write safer, more consistent JavaScript.
🧱 Understanding Scope: Function Scope vs. Block Scope
In JavaScript, scope determines where a variable is accessible. Let's start with var:
function testVar() {
if (true) {
var a = 10;
}
console.log(a); // 10; var declarations are not block-scoped
}
testVar();
Although a is declared inside the if block, it is accessible throughout the function. This is because var has function scope: ordinary blocks do not create a separate scope for it.
let and const behave differently:
function testLet() {
if (true) {
let b = 20;
}
console.log(b); // Error: b is not accessible outside the if block
}
testLet();
let and const have block scope: they are accessible only within their enclosing {} block. In loops and conditionals, this keeps variables local to the block and prevents them from interfering with the outer scope.
🌄 Hoisting: var vs. let and const
Hoisting describes behavior that makes declarations appear to move to the top of their scope. With var, you can access a variable before its declaration, although this is best avoided.
console.log(x); // undefined
var x = 5;
Here, var x is hoisted, but the assignment =5 is not, so the code logs undefined rather than throwing an error.
let and const behave differently:
console.log(y); // Error: cannot access y before its declaration
let y = 10;
Variables declared with let and const remain in the temporal dead zone (TDZ) until their declarations initialize them. Accessing them before that point throws an error, preventing the use of uninitialized variables.
📌 The Key Difference Between let and const
Both let and const have block scope and cannot be accessed before initialization. Their main difference is:
- Variables declared with let can be reassigned.
- Variables declared with const cannot be reassigned after initialization; their binding cannot change.
For example:
let age = 25;
age = 30; // Valid: let allows reassignment
const name = 'Alice';
name = 'Bob'; // Error: const does not allow reassignment
Use const when a variable will not be reassigned. This prevents accidental changes and makes code safer and easier to maintain.
const by default, and use let only when reassignment is needed.🧩 Can Objects Declared with const Change?
This is a common source of confusion. const does not make a value completely immutable; it prevents the variable's reference from changing.
Think of a fixed mailbox number as a const binding. The number stays the same, but you can put different letters in the mailbox, just as you can change an object's properties.
const person = {
name: 'Tom',
age: 18,
};
person.age = 20; // Valid: changes an object property
person.name = 'Jerry'; // Also valid
person = {}; // Error: cannot reassign a constant
const preserves the reference held by the variable, but the object's contents can still change.
Object.freeze() to freeze an object and prevent its properties from being changed.const person = Object.freeze({
name: 'Tom',
age: 18,
});
person.age = 20; // Does not change the frozen property
console.log(person.age); // 18
🎉 A Practical Example
This example shows when to use let and const.
function showScores() {
const scores = [90, 80, 70];
for (let i = 0; i < scores.length; i++) {
// let gives i block scope and a separate binding for each iteration
console.log('Score ' + i + ': ' + scores[i]);
}
// scores cannot be assigned a new array, but its contents can change
scores.push(85);
console.log(scores);
}
showScores();
scores uses const to prevent accidental reassignment to a new array. i uses let because the loop counter must be updated on each iteration.
❓ Knowledge Check
Q1: What are the main differences between var, let, and const? var has function scope and can be accessed before its declaration because of hoisting. let and const have block scope and cannot be accessed before initialization; const also prevents reassignment.
Q2: Why does accessing a let or const variable before its declaration throw an error? The temporal dead zone prevents access before initialization.
Q3: Can you change the properties of an object declared with const? Yes. const keeps the variable's reference unchanged, but the object's properties can still change.
🧪 Exercises
- Write a function that uses a let counter to log the numbers 1 through 5 in a loop.
function printNumbers() {
// Write your code here
}
printNumbers();
- Declare an object with const. Try changing its properties, then reassigning it, and observe the results.
const car = {
brand: 'Toyota',
year: 2020,
};
// Try changing car's properties and reassigning car here
🎉 You now understand let, const, scope, and hoisting! Keep practicing these fundamentals to write better JavaScript.
Getting Started with ES6
Learn what ES6 is, how it differs from ES5, why it matters, and how to run it in browsers, transpile it with Babel, and practice online.
Arrow Function Syntax and Behavior
Learn how ES6 arrow functions work, how they differ from regular functions, and when to use them in frontend projects.
