Home » JavaScript const Keyword: A Complete Tutorial with Examples

JavaScript const Keyword: A Complete Tutorial with Examples

The const keyword in JavaScript is used to declare variables that have a constant reference, meaning their values cannot be reassigned after they are declared.

Introduced in ES6 (ECMAScript 2015), const is similar to let in that it is block-scoped, but with the additional restriction of preventing reassignment.

Why Use const?

Immutable References: A variable declared with const cannot be reassigned.
Block Scope: Like let, const is block-scoped, making it safer to use inside blocks.
Signal Intent: Using const indicates that the variable should not change, providing more clarity and reducing bugs.

Syntax

const variableName = value;

variableName: The name of the constant variable.
value: The initial value assigned to the variable. A const variable must be initialized during declaration.

Examples

1. Basic Usage of const

const PI = 3.14;
console.log(PI); // Output: 3.14

PI = 3.14159; // Error: Assignment to constant variable.

Explanation

const PI = 3.14; declares a constant PI with the value 3.14.
Attempting to reassign PI with a new value results in an error, as PI is declared with const.

2. Block Scope with const

Like let, const is block-scoped. This means that a const variable is only accessible within the block {} in which it is declared.

if (true) {
  const greeting = 'Hello, World!';
  console.log(greeting); // Output: "Hello, World!"
}

console.log(greeting); // Error: greeting is not defined

Explanation

greeting is declared inside the if block, so it is not accessible outside of it.
Attempting to access greeting outside the block results in an error.

3. Difference Between let and const

The key difference between let and const is that const does not allow reassignment. You must initialize a const variable at the time of declaration.

let age = 25;
age = 30; // This is allowed

const name = 'Alice';
name = 'Bob'; // Error: Assignment to constant variable.

Explanation

age is declared with let, so it can be reassigned.
name is declared with const, so trying to reassign it results in an error.

4. Arrays with const

While you cannot reassign a const variable, you can modify the contents of an array declared with const.

const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // Output: [1, 2, 3, 4]

numbers = [5, 6, 7]; // Error: Assignment to constant variable.

Explanation

You can modify the elements within the numbers array because the reference to the array itself has not changed.
Attempting to reassign the numbers variable to a new array results in an error.

5. Objects with const

Similarly, you can modify the properties of an object declared with const, but you cannot reassign the object itself.

const person = {
  name: 'Alice',
  age: 25
};

person.age = 30; // This is allowed
console.log(person); // Output: { name: 'Alice', age: 30 }

person = { name: 'Bob', age: 40 }; // Error: Assignment to constant variable.

Explanation

The properties of the person object can be modified because the reference to the object remains the same.
Reassigning the person variable to a new object results in an error.

6. Block Scope with Loops

const is block-scoped and works well inside loops, but it must be declared for each iteration.

for (let i = 0; i < 3; i++) {
  const message = `Iteration ${i}`;
  console.log(message);
}

console.log(message); // Error: message is not defined

Explanation

The message variable declared inside the loop is block-scoped and only exists within each iteration.
Attempting to access message outside the loop results in an error.

7. Constants with Default Values in Functions

You can use const to define default values for function parameters.

function greet(name = 'Guest') {
  const greeting = `Hello, ${name}!`;
  console.log(greeting);
}

greet('Alice'); // Output: "Hello, Alice!"
greet(); // Output: "Hello, Guest!"

Explanation

The greet function uses const to declare a greeting that combines the name parameter with a default value (‘Guest' if no argument is passed).

8. Chaining and const

When working with multiple const declarations, chaining assignments in a single line is not allowed.

const a = 5, b = 10;
const sum = a + b;

console.log(sum); // Output: 15

Explanation

You can declare multiple constants in a single statement by separating them with commas.
However, you cannot do something like const a = 5 = b = 10; which would cause an error.

Summary

The const keyword in JavaScript is used for declaring variables that you don’t want to be reassigned.

It is a best practice to use const for variables that should not change to make your code more predictable and reduce errors.

Key Points

Immutable Reference: A const variable’s reference cannot be reassigned. However, the contents of objects and arrays declared with const can be modified.
Block Scope: const is block-scoped, meaning it is only accessible within the block {} where it is declared.
Must Be Initialized: A const variable must be initialized at the time of declaration.
Clear Intent: Use const for values that should not change, signaling intent and reducing potential bugs.

You may also like