JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Const


In JavaScript, const is a keyword used to declare variables whose values are constant, meaning they cannot be reassigned after initialization. Introduced in ES6 (ECMAScript 2015), const is commonly used to store values that should remain unchanged throughout the program, such as configuration settings, fixed numbers, or references to objects and arrays.

Understanding const is essential for writing predictable and maintainable code. It prevents accidental reassignment of values, reduces bugs, and communicates clearly to other developers which variables are intended to stay constant.

In this chapter, you will learn about const, its rules, behavior with primitive and complex data types, scope, practical examples, common mistakes, best practices, and real-world applications.

What Is const

A variable declared with const must be initialized at the time of declaration. Once assigned, its value cannot be reassigned.

Example

const pi = 3.1416;
console.log(pi); // Outputs: 3.1416

Attempting to reassign a const variable will result in an error:

// pi = 3.14; // TypeError: Assignment to constant variable

Scope of const

Like let, const is block-scoped, meaning the variable is only accessible within the block where it is defined. This prevents unintentional access or modification from outside the block.

Example

{
    const name = "Ananya";
    console.log(name); // Outputs: Ananya
}

// console.log(name); // ReferenceError: name is not defined

Variables declared with const cannot be redeclared or accessed outside their block.

Nested Block Example

const name = "Sanya";

{
    const name = "Riya"; // Separate constant in inner block
    console.log(name); // Outputs: Riya
}

console.log(name); // Outputs: Sanya

Each block maintains its own separate const variable.

Behavior with Primitive Values

Primitive values include numbers, strings, booleans, null, undefined, and symbols. Once assigned to a const variable, these values cannot be changed.

Example

const age = 22;
console.log(age); // 22

// age = 23; // TypeError: Assignment to constant variable

Behavior with Objects and Arrays

const does not make objects or arrays immutable. It only prevents reassignment of the variable itself. However, the contents of an object or array can still be modified.

Object Example

const girl = { name: "Diya", age: 22 };
console.log(girl.name); // Diya

girl.name = "Riya"; // Allowed
console.log(girl.name); // Riya

// girl = { name: "Mira" }; // TypeError: Assignment to constant variable

Array Example

const girls = ["Ananya", "Ishita", "Sanya"];
girls.push("Riya"); // Allowed
console.log(girls); // ["Ananya", "Ishita", "Sanya", "Riya"]

// girls = ["Mira"]; // TypeError: Assignment to constant variable

This distinction is important when working with data structures in JavaScript.

Loop Example with const

const can be used inside loops for variables that do not change during each iteration.

const girls = ["Ananya", "Ishita", "Sanya", "Riya"];

for (const girl of girls) {
    console.log(girl + " is attending the workshop.");
}

Output:

Ananya is attending the workshop.
Ishita is attending the workshop.
Sanya is attending the workshop.
Riya is attending the workshop.

Here, girl is a block-scoped constant for each iteration of the loop.

Practical Examples

Example 1: Fixed Values

const pi = 3.1416;
const maxUsers = 100;

console.log("Value of Pi:", pi);
console.log("Maximum users allowed:", maxUsers);

Example 2: Constant Object

const girl = { name: "Mira", age: 21 };
girl.age = 22;
console.log(girl); // { name: "Mira", age: 22 }

Example 3: Constant Array

const names = ["Ananya", "Ishita", "Sanya"];
names.push("Riya");
console.log(names); // ["Ananya", "Ishita", "Sanya", "Riya"]

Common Mistakes

  • Declaring a const variable without initialization.

  • Attempting to reassign a const variable.

  • Misunderstanding that const makes objects immutable.

  • Using const for variables that need reassignment.

Best Practices

  • Use const by default, especially for values that should not change.

  • Use let only for variables that need reassignment.

  • Declare constants in uppercase letters to indicate they should not change (optional convention).

  • Avoid unnecessary global constants to prevent conflicts.

Example of Naming Convention

const MAX_USERS = 50;
const PI = 3.1416;

Real-World Applications

  • Storing configuration settings or fixed values like API endpoints.

  • Keeping mathematical constants, such as Pi or gravitational constant.

  • Declaring references to objects or arrays that should not be reassigned.

  • Preventing accidental reassignment in critical calculations or loops.

Example: Application Settings

const config = {
    apiUrl: "https://example.com/api",
    maxRetries: 5,
    timeout: 3000
};

config.timeout = 5000; // Allowed
// config = {}; // Not allowed

Example: User List

const users = ["Ananya", "Ishita", "Sanya"];
users.push("Riya");
console.log(users); // ["Ananya", "Ishita", "Sanya", "Riya"]

This demonstrates how const can safely hold references to arrays while allowing controlled modifications.

Summary of JS Const

The const keyword in JavaScript declares block-scoped variables whose value cannot be reassigned after initialization. It provides safety, predictability, and better code readability. While primitive values cannot be changed, objects and arrays assigned to const can still be modified internally. const is ideal for fixed values, configuration objects, arrays, and mathematical constants. Using const alongside let helps maintain clear, reliable, and maintainable JavaScript code.


Practice Questions

Q1. How do you declare a constant variable named country with the value "India" using const?

Q2. How do you demonstrate that reassignment of a const variable causes an error?

Q3. How do you declare a constant object car and modify one of its properties (e.g., change color)?

Q4. How do you declare a constant array fruits with three elements and add a fourth element to it?

Q5. How do you show that redeclaring a const variable in the same scope causes an error?

Q6. How do you demonstrate that const is block-scoped using an if block?

Q7. How do you create a constant object user and log one of its properties (like user.name)?

Q8. How do you explain the difference between modifying an object vs. reassigning a const object? Show with code.

Q9. What happens if you declare a const variable without assigning a value? Show with code.

Q10. How do you write a const variable named MAX_SCORE with a numeric value and use it in a condition?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top