LearnContact
Lesson 635 min read

JavaScript Constants

Learn how JavaScript constants work using the const keyword, including declaration, initialization, reassignment rules, arrays, objects, scope, mutation, and best practices.

Introduction

Many values in a JavaScript program should remain connected to the same variable throughout their lifetime. A course name, application name, tax rate, API configuration object, product collection, or function reference may not need to be reassigned after it is created.

JavaScript provides the const keyword for creating variable bindings that cannot be reassigned. Using const clearly communicates that the variable name should continue referring to the same value or object during its accessible lifetime.

Understanding const requires more than knowing that reassignment is prohibited. Arrays and objects declared with const can still have their contents modified. This difference between reassignment and mutation is one of the most important concepts for JavaScript beginners.

What You Will Learn
  • What a constant is in JavaScript.
  • Why JavaScript programs use constants.
  • How to declare constants with const.
  • Why const variables must be initialized.
  • Why const variables cannot be reassigned.
  • The differences between const, let, and var.
  • How to choose between a variable and a constant.
  • How constants store primitive values.
  • How const works with arrays.
  • How const works with objects.
  • The difference between reassignment and mutation.
  • How block scope affects constants.
  • How constants behave before declaration.
  • How Object.freeze() differs from const.
  • How constants are used in real applications.

What is a Constant?

In JavaScript, a constant is a variable binding created with the const keyword that cannot be reassigned after initialization.

Simple Constant
const courseName = 'JavaScript';

console.log(courseName);
Output

The variable courseName is declared using const and initialized with the string JavaScript. The courseName variable cannot later be assigned a completely different value.

Constant Structure
const courseName = 'JavaScript';
│     │              │
│     │              └── Initial Value
│     │
│     └── Constant Name
│
└── Declaration Keyword
Simple Definition
  • const creates a variable binding.
  • The variable must receive an initial value.
  • The variable cannot later be reassigned.
  • The variable still follows JavaScript scope rules.
  • Objects and arrays stored with const can still be mutated.

Why Do We Need Constants?

Constants make the intention of code clearer. When a developer sees const, they immediately know that the variable is not expected to receive a completely different value later.

Prevent Reassignment

const prevents a variable from accidentally receiving a completely different value.

Improve Readability

Readers immediately know that reassignment is not expected.

Reduce Mistakes

Accidental reassignment produces an error instead of silently changing the variable.

Show Intent

const clearly communicates how a variable is intended to be used.

Cleaner Code

Using const by default makes changeable state easier to identify.

Store Configuration

Constants are commonly used for configuration values and application settings.

Clear Intent
const courseName = 'Core JavaScript';
const totalLessons = 27;

let currentLesson = 6;

currentLesson = 7;

The code clearly communicates that courseName and totalLessons should not be reassigned, while currentLesson is expected to change.

Real-World Analogy

Think of const as assigning a permanent label to one particular storage location. The label cannot be moved to a different box.

Constant Analogy
const courseName = 'JavaScript'

courseName
    │
    ▼
┌──────────────────────┐
│     'JavaScript'     │
└──────────────────────┘

The connection cannot be changed:

courseName ─────X─────▶ 'Python'

❌ Reassignment Not Allowed

For primitive values, this appears similar to having an unchangeable value. For objects and arrays, however, the connection remains fixed while the contents of the connected object or array may still change.

Object Analogy
const user

user
  │
  ▼
┌──────────────────────┐
│ name: 'Rahul'        │
│ age: 22              │
└──────────────────────┘

The connection stays the same.

But contents may change:

age: 22  →  age: 23

The const Keyword

The const keyword was introduced in ECMAScript 2015, also known as ES6. It is now one of the standard ways to declare variables in modern JavaScript.

const Syntax
const variableName = value;
Examples
const name = 'Rahul';
const age = 22;
const isActive = true;
const price = 499.99;
Modern JavaScript Recommendation
  • Use const when reassignment is not required.
  • Use let when reassignment is required.
  • Avoid var for most new JavaScript code.
  • Start with const and change to let only when necessary.

Declaring a Constant

A constant is declared using the const keyword followed by a valid variable name, the assignment operator, and an initial value.

Constant Declaration
const language = 'JavaScript';

console.log(language);
Output
Declaration Process
const language = 'JavaScript';
  │       │          │
  │       │          └── Initial Value
  │       │
  │       └── Identifier
  │
  └── Declaration Keyword

Constants Must Be Initialized

Unlike a variable declared with let or var, a const variable must receive a value at the moment it is declared.

Valid Constant
const courseName = 'JavaScript';
Invalid Constant
const courseName;
Result

JavaScript requires immediate initialization because the const binding cannot be assigned later.

Not Allowed
const courseName;

courseName = 'JavaScript';
Important Rule
  • const declaration and initialization happen together.
  • You cannot declare an empty const variable.
  • You cannot assign its first value later.
  • Every const declaration requires an initializer.

Constants Cannot Be Reassigned

After a const variable has been initialized, it cannot be assigned a completely different value.

Invalid Reassignment
const courseName = 'JavaScript';

courseName = 'Python';
Result
Reassignment Attempt
Initial State

courseName → 'JavaScript'

Attempt

courseName → 'Python'

Result

❌ TypeError

The original const binding remains unchanged because JavaScript prevents reassignment.

Declaration vs Reassignment

Declaration creates the variable. Initialization gives it the first value. Reassignment attempts to replace the existing value with another value.

Declaration and Initialization
const price = 500;
Reassignment
price = 750;
Result

Declaration

Creates the constant variable name.

Initialization

Provides the required first value.

Reassignment

Attempts to replace the existing value and is prohibited for const.

const vs let

Both const and let are modern JavaScript declaration keywords. Both are block-scoped, but they differ in reassignment and initialization requirements.

const vs let
Feature                 const       let
----------------------------------------------
Block Scoped?           Yes         Yes
Can Reassign?           No          Yes
Can Redeclare?          No          No
Must Initialize?        Yes         No
Modern JavaScript?      Yes         Yes
const Example
const courseName = 'JavaScript';

// ❌ Not allowed
courseName = 'Python';
let Example
let currentLesson = 6;

// ✅ Allowed
currentLesson = 7;

console.log(currentLesson);
Output

const vs var

const and var differ significantly in scope, reassignment, redeclaration, and modern usage.

const vs var
Feature                 const       var
----------------------------------------------
Can Reassign?           No          Yes
Can Redeclare?          No          Yes
Block Scoped?           Yes         No
Function Scoped?        No*         Yes
Must Initialize?        Yes         No
Modern Recommendation   Yes         Rare

* const may exist inside a function,
  but it follows block scope.
Modern Choice
  • Use const for values that do not require reassignment.
  • Use let for values that require reassignment.
  • Use var mainly when working with older code or when its specific behavior is intentionally required.

Variable or Constant?

In JavaScript, const still creates a variable. The important difference is that the variable binding cannot be reassigned.

Choosing the Keyword
// Does not need reassignment
const userName = 'Rahul';

// Does need reassignment
let score = 0;

score = 10;
score = 20;
Decision Flow
Do you need to reassign the variable?
              │
        ┌─────┴─────┐
        │           │
       No          Yes
        │           │
        ▼           ▼
      const         let
Simple Rule
  • Start with const.
  • If reassignment becomes necessary, use let.
  • Do not use let only because a value might theoretically change someday.
  • Choose based on whether the variable is actually reassigned.

Constant Naming Rules

Constants follow the same identifier naming rules as other JavaScript variables.

  • A constant name can contain letters.
  • A constant name can contain digits.
  • A constant name can contain an underscore (_).
  • A constant name can contain a dollar sign ($).
  • A constant name cannot begin with a digit.
  • A constant name cannot contain spaces.
  • A constant name cannot contain most special characters.
  • A JavaScript reserved keyword cannot be used as a constant name.
  • Constant names are case-sensitive.
Valid Constant Names
const courseName = 'JavaScript';
const totalLessons = 27;
const _internalValue = 100;
const $price = 500;
const version2 = '2.0';

Constant Naming Conventions

Not every variable declared with const should be written in uppercase letters. JavaScript developers usually use camelCase for normal const variables.

Normal const Variables
const firstName = 'Rahul';
const productPrice = 500;
const currentUser = {
    name: 'Rahul'
};

Uppercase names are commonly reserved for values that are treated as fixed configuration constants or application-wide constants.

Uppercase Constants
const MAX_LOGIN_ATTEMPTS = 3;
const API_TIMEOUT = 5000;
const DEFAULT_LANGUAGE = 'en';
const TAX_RATE = 0.18;
Naming Recommendation
  • Use camelCase for ordinary const variables.
  • Use UPPER_SNAKE_CASE for truly fixed configuration-style constants when your project follows that convention.
  • Do not write every const variable in uppercase.
  • Follow the naming style used consistently by your project.

Primitive Constants

When const stores a primitive value such as a string, number, boolean, null, bigint, symbol, or undefined, the variable cannot be reassigned to another value.

Primitive Constants
const courseName = 'JavaScript';
const totalLessons = 27;
const isFree = true;
const discount = null;

console.log(courseName);
console.log(totalLessons);
console.log(isFree);
console.log(discount);
Output

String Constants

A string stored in a const variable cannot be replaced with another string through reassignment.

String Constant
const applicationName = 'PrograMinds';

console.log(applicationName);
Output
Invalid String Reassignment
const applicationName = 'PrograMinds';

applicationName = 'DevJourney';
Result

Number Constants

Numbers that should not be reassigned can be stored using const.

Number Constants
const totalLessons = 27;
const taxRate = 0.18;
const maximumScore = 100;

console.log(totalLessons);
console.log(taxRate);
console.log(maximumScore);
Output

Boolean Constants

Boolean values that do not need reassignment can also be declared with const.

Boolean Constants
const isCourseFree = true;
const hasCertificate = false;

console.log(isCourseFree);
console.log(hasCertificate);
Output

const with Arrays

Arrays are objects in JavaScript. When an array is assigned to a const variable, the variable cannot be reassigned to a different array.

Constant Array
const technologies = ['HTML', 'CSS', 'JavaScript'];

console.log(technologies);
Output

However, the contents of the array can still be modified.

Modifying Array Elements

A const array can still be mutated by adding, removing, or changing its elements.

Adding an Element
const technologies = ['HTML', 'CSS'];

technologies.push('JavaScript');

console.log(technologies);
Output
Changing an Element
const technologies = ['HTML', 'CSS', 'JavaScript'];

technologies[1] = 'Advanced CSS';

console.log(technologies);
Output
Why is This Allowed?
  • The technologies variable still refers to the same array.
  • Only the contents inside the array are changing.
  • The variable itself is not being reassigned.
  • const prevents reassignment, not mutation.

Reassigning a Constant Array

Although the contents can change, the const variable cannot be assigned a completely different array.

Invalid Array Reassignment
const technologies = ['HTML', 'CSS'];

technologies = ['JavaScript', 'React'];
Result
Array Behavior
Allowed:

technologies
     │
     ▼
['HTML', 'CSS']
     │
     ▼
['HTML', 'CSS', 'JavaScript']

Same Array → Contents Changed ✅


Not Allowed:

technologies
     │
     ▼
['HTML', 'CSS']

Attempt to reconnect:

technologies ─────▶ ['React', 'Next.js']

Different Array ❌

const with Objects

Objects declared with const follow the same general rule as arrays. The variable cannot be reassigned, but object properties can still be modified.

Constant Object
const student = {
    name: 'Rahul',
    age: 22,
    course: 'JavaScript'
};

console.log(student);
Output

Modifying Object Properties

Properties of an object stored using const can be changed, added, or removed.

Changing a Property
const student = {
    name: 'Rahul',
    age: 22
};

student.age = 23;

console.log(student);
Output
Adding a Property
const student = {
    name: 'Rahul'
};

student.course = 'JavaScript';

console.log(student);
Output
Removing a Property
const student = {
    name: 'Rahul',
    age: 22
};

delete student.age;

console.log(student);
Output

Reassigning a Constant Object

A const object variable cannot be assigned a completely different object.

Invalid Object Reassignment
const student = {
    name: 'Rahul'
};

student = {
    name: 'Amit'
};
Result

Reassignment vs Mutation

Understanding the difference between reassignment and mutation is essential when working with const.

Comparison
Reassignment
--------------------------------
Variable points to a new value.

user = newObject;

With const: ❌ Not Allowed


Mutation
--------------------------------
Contents of the existing object change.

user.age = 23;

With const: ✅ Allowed
Mutation Example
const user = {
    name: 'Rahul',
    age: 22
};

// Mutation
user.age = 23;

console.log(user);
Output
Reassignment Example
const user = {
    name: 'Rahul'
};

// Reassignment
user = {
    name: 'Amit'
};
Result
Remember This Difference
  • Reassignment changes what the variable refers to.
  • Mutation changes the contents of an existing object or array.
  • const prevents reassignment.
  • const does not automatically prevent mutation.

Nested Objects and Arrays

Objects can contain arrays and other objects. A const variable still allows changes inside these nested structures.

Nested Data
const course = {
    name: 'JavaScript',
    instructor: {
        name: 'Rahul'
    },
    topics: ['Variables', 'Constants']
};

course.instructor.name = 'Amit';
course.topics.push('Data Types');

console.log(course);
Output

The course variable still refers to the same object, so changes to nested data are allowed.

Block Scope

Constants are block-scoped. A constant declared inside a block can only be accessed within that block and its nested scopes.

Block-Scoped Constant
if (true) {
    const message = 'Inside the block';

    console.log(message);
}
Output
Outside the Block
if (true) {
    const message = 'Inside the block';
}

console.log(message);
Result
Block Scope
Outside Block
│
├── message is not available
│
└── if Block {
        const message = 'Hello';
              │
              └── Available Here
    }

Constants Inside Functions

A constant declared inside a function is only accessible within its allowed function or nested block scope.

Function Constant
function showCourse() {
    const courseName = 'JavaScript';

    console.log(courseName);
}

showCourse();
Output
Outside the Function
function showCourse() {
    const courseName = 'JavaScript';
}

console.log(courseName);
Result

Global Constants

A const declaration placed at the top level of a script or module can be accessed by code within its applicable outer scope.

Outer-Scope Constant
const APPLICATION_NAME = 'PrograMinds';

function showApplicationName() {
    console.log(APPLICATION_NAME);
}

showApplicationName();

console.log(APPLICATION_NAME);
Output
Avoid Excessive Global State
  • Global values can be accessed from many parts of a program.
  • Too many global declarations can make large applications harder to maintain.
  • Keep constants in the smallest practical scope.
  • Use modules and configuration files in larger applications.

Constant Shadowing

A constant in an inner scope can use the same name as a variable in an outer scope. The inner declaration shadows the outer declaration within that scope.

Constant Shadowing
const message = 'Global Message';

function showMessage() {
    const message = 'Local Message';

    console.log(message);
}

showMessage();

console.log(message);
Output
Shadowing
Outer Scope

message = 'Global Message'
        │
        └── Function Scope
              │
              └── message = 'Local Message'
                    │
                    └── Used inside function

Temporal Dead Zone

A const variable cannot be accessed before the execution reaches its declaration. The period between entering the scope and reaching the declaration is commonly called the Temporal Dead Zone.

Access Before Declaration
console.log(courseName);

const courseName = 'JavaScript';
Result
Temporal Dead Zone
Enter Scope
    │
    ▼
┌─────────────────────────┐
│   Temporal Dead Zone    │
│                         │
│ courseName unavailable  │
└─────────────────────────┘
    │
    ▼
const courseName = 'JavaScript';
    │
    ▼
courseName is now accessible
Important
  • const declarations are associated with their scope before execution reaches the declaration.
  • They cannot be safely accessed before initialization.
  • Accessing them too early causes a ReferenceError.
  • This topic will be explained further in the Hoisting lesson.

Constants and Hoisting

const declarations are commonly described as being hoisted, but unlike var variables, they are not initialized with undefined for normal access before their declaration.

const Before Declaration
console.log(price);

const price = 500;
Result
Do Not Use Constants Before Declaration
  • Declare constants before using them.
  • Do not expect const to behave like var.
  • The detailed mechanics will be covered in Lesson 15: Hoisting.

Object.freeze()

If you want to prevent direct changes to the own properties of an object, JavaScript provides Object.freeze().

Freezing an Object
const settings = Object.freeze({
    theme: 'dark',
    language: 'en'
});

settings.theme = 'light';

console.log(settings.theme);
Output

In strict mode, attempting certain modifications to a frozen object can throw a TypeError. In non-strict code, some failed modifications may be ignored.

const vs Object.freeze()
const
--------------------------------
Prevents variable reassignment.

const user = {...};

user = newObject;       ❌
user.name = 'Amit';     ✅


Object.freeze()
--------------------------------
Prevents changes to direct
properties of the frozen object.

user.name = 'Amit';     ❌

Object.freeze() is Shallow

Object.freeze() only freezes the direct properties of an object. Nested objects are not automatically frozen.

Shallow Freeze
const user = Object.freeze({
    name: 'Rahul',
    address: {
        city: 'Mumbai'
    }
});

user.address.city = 'Pune';

console.log(user.address.city);
Output
Shallow Freeze
  • The outer object is frozen.
  • The nested address object is a separate object.
  • The nested object is not automatically frozen.
  • Deep immutability requires additional techniques.

Constants in Calculations

Constants are commonly used in calculations when input values should not be reassigned.

Price Calculation
const productPrice = 1000;
const quantity = 3;
const taxRate = 0.18;

const subtotal = productPrice * quantity;
const taxAmount = subtotal * taxRate;
const finalAmount = subtotal + taxAmount;

console.log('Subtotal:', subtotal);
console.log('Tax:', taxAmount);
console.log('Final Amount:', finalAmount);
Output

Each result is declared with const because none of these variables needs to be reassigned later in this example.

Constants in Functions

Local constants are commonly used inside functions for intermediate values that do not require reassignment.

Function Constants
function calculateTotal(price, quantity) {
    const subtotal = price * quantity;
    const tax = subtotal * 0.18;
    const total = subtotal + tax;

    return total;
}

console.log(calculateTotal(500, 2));
Output

Using const makes it clear that subtotal, tax, and total are calculated once during each function call and are not reassigned afterward.

Constants in Configuration

Constants are often used for application settings and configuration values.

Application Configuration
const APP_NAME = 'PrograMinds';
const DEFAULT_LANGUAGE = 'en';
const MAX_LOGIN_ATTEMPTS = 3;
const REQUEST_TIMEOUT = 5000;

console.log(APP_NAME);
console.log(DEFAULT_LANGUAGE);
console.log(MAX_LOGIN_ATTEMPTS);
console.log(REQUEST_TIMEOUT);
Output
Configuration Object
const appConfig = {
    name: 'PrograMinds',
    version: '1.0.0',
    language: 'en',
    theme: 'dark'
};

console.log(appConfig);

Complete Constants Example

The following example demonstrates primitive constants, a changeable variable, a const object, a const array, calculations, and mutation.

course-dashboard.js
const COURSE_NAME = 'Core JavaScript';
const TOTAL_LESSONS = 27;

const student = {
    name: 'Rahul',
    completedLessons: 5
};

const completedTopics = [
    'Introduction',
    'History',
    'JavaScript Engine',
    'How JavaScript Works',
    'Variables'
];

let currentLesson = 6;

const progress =
    (student.completedLessons / TOTAL_LESSONS) * 100;

console.log('Course:', COURSE_NAME);
console.log('Student:', student.name);
console.log('Current Lesson:', currentLesson);
console.log('Progress:', progress.toFixed(2) + '%');

// Complete the current lesson
student.completedLessons = 6;
completedTopics.push('Constants');

currentLesson = 7;

console.log('Completed Lessons:', student.completedLessons);
console.log('Topics:', completedTopics);
console.log('Next Lesson:', currentLesson);
Output
Program Structure
Fixed Course Information
        │
        ├── COURSE_NAME
        └── TOTAL_LESSONS
                │
                ▼
Student Object ───────▶ Properties Can Change
                │
                ▼
Topics Array ─────────▶ Elements Can Change
                │
                ▼
currentLesson ────────▶ Reassigned with let
                │
                ▼
Calculate and Display Progress

Real-World Applications

Constants are used throughout modern JavaScript applications.

Configuration

Store application names, versions, limits, and default settings.

API Settings

Store request timeouts, endpoint collections, and configuration objects.

E-Commerce

Store product references, tax rates, and calculation results.

Games

Store game configuration, maximum levels, and fixed rules.

UI Components

Store element references, configuration objects, and component data.

Collections

Store arrays that may be modified without reassigning the variable.

User Data

Store object references while allowing property updates.

Calculations

Store intermediate and final results that do not require reassignment.

Common Beginner Mistakes

Avoid These Mistakes
  • Declaring a const variable without an initial value.
  • Trying to reassign a const variable.
  • Thinking const means the value is deeply immutable.
  • Thinking a const array cannot be modified.
  • Thinking a const object cannot have its properties changed.
  • Confusing reassignment with mutation.
  • Using let for every variable even when reassignment never occurs.
  • Writing every const variable name in uppercase.
  • Trying to access a const variable before its declaration.
  • Expecting const to behave like var before declaration.
  • Redeclaring a const variable in the same scope.
  • Assuming Object.freeze() deeply freezes nested objects.
  • Using global constants unnecessarily.
  • Using meaningless constant names.
  • Changing nested data without understanding reference behavior.
Common Mistakes
// ❌ Missing initializer
const name;

// ❌ Reassignment
const score = 100;
score = 200;

// ❌ Redeclaration
const city = 'Mumbai';
const city = 'Pune';

// ❌ Access before declaration
console.log(courseName);
const courseName = 'JavaScript';

Best Practices

  • Use const by default.
  • Use let only when reassignment is required.
  • Avoid var in modern JavaScript unless its behavior is intentionally needed.
  • Always initialize const variables during declaration.
  • Use meaningful and descriptive names.
  • Use camelCase for normal const variables.
  • Use UPPER_SNAKE_CASE only for appropriate fixed configuration-style constants.
  • Do not assume const makes objects and arrays immutable.
  • Understand the difference between reassignment and mutation.
  • Keep constants in the smallest practical scope.
  • Declare constants before using them.
  • Avoid unnecessary global constants.
  • Group related configuration values when appropriate.
  • Use Object.freeze() only when shallow property protection is actually required.
  • Remember that Object.freeze() is shallow.
  • Prefer predictable data structures and intentional mutations.
  • Do not change object or array contents unexpectedly from unrelated parts of an application.
Recommended Style
const courseName = 'Core JavaScript';
const totalLessons = 27;

const student = {
    name: 'Rahul',
    completedLessons: 6
};

let currentLesson = 6;

currentLesson = 7;

Frequently Asked Questions

What is a constant in JavaScript?

A constant is a variable binding declared with const that cannot be reassigned after initialization.

Which keyword creates a constant?

JavaScript uses the const keyword.

Must a const variable be initialized?

Yes. A const variable must receive an initial value when it is declared.

Can a const variable be reassigned?

No. Attempting to reassign it causes an error.

Can a const variable be redeclared?

It cannot be redeclared in the same scope.

What is the difference between const and let?

Both are block-scoped, but let allows reassignment while const does not.

Should I use const or let?

Use const by default and use let when the variable actually needs reassignment.

Can a const array change?

Yes. Array elements can be added, removed, or modified because const prevents reassignment of the variable, not mutation of the array.

Can a const object change?

Yes. Object properties can be added, removed, or modified.

Can I assign a new array to a const variable?

No. Assigning a completely different array is reassignment and is not allowed.

Can I assign a new object to a const variable?

No. A const variable cannot be reassigned to a different object.

What is mutation?

Mutation means changing the contents of an existing object or array without reassigning the variable.

What is reassignment?

Reassignment means making an existing variable refer to a different value.

Is const block-scoped?

Yes. const variables are block-scoped.

Can I use a const variable before declaration?

No. Accessing it before initialization causes a ReferenceError because of the Temporal Dead Zone.

Are const declarations hoisted?

They are associated with their scope before execution reaches the declaration, but they cannot be accessed before initialization.

Does const make an object immutable?

No. const only prevents reassignment of the variable binding.

What does Object.freeze() do?

Object.freeze() prevents direct modifications to the own properties of the frozen object.

Does Object.freeze() deeply freeze an object?

No. Object.freeze() is shallow, so nested objects are not automatically frozen.

Should every const name be uppercase?

No. Normal const variables usually use camelCase. Uppercase naming is commonly reserved for fixed configuration-style constants according to project conventions.

Key Takeaways

  • JavaScript uses const to create non-reassignable variable bindings.
  • A const variable must be initialized during declaration.
  • A const variable cannot be reassigned.
  • A const variable cannot be redeclared in the same scope.
  • const is block-scoped.
  • Use const by default in modern JavaScript.
  • Use let when reassignment is required.
  • const and let are preferred over var for most modern code.
  • Normal const variables commonly use camelCase.
  • Configuration-style constants may use UPPER_SNAKE_CASE.
  • Primitive values stored with const cannot be replaced through reassignment.
  • Arrays declared with const can still be modified.
  • Objects declared with const can still be modified.
  • const prevents reassignment, not mutation.
  • Changing an array element is mutation.
  • Changing an object property is mutation.
  • Assigning a new array or object is reassignment.
  • Constants cannot be accessed before initialization.
  • const declarations are affected by the Temporal Dead Zone.
  • Object.freeze() can prevent direct property modifications.
  • Object.freeze() is shallow.
  • Constants are useful for configuration, calculations, collections, and application data.
  • Keep constants in the smallest practical scope.
  • Meaningful constant names improve readability and maintainability.

Summary

The const keyword is one of the most important tools in modern JavaScript. It creates a variable binding that must be initialized immediately and cannot later be reassigned.

Using const makes code easier to understand because it clearly communicates that reassignment is not expected. For this reason, modern JavaScript developers commonly use const by default and switch to let only when a variable genuinely needs reassignment.

The most important rule to understand is that const does not automatically make values immutable. Arrays and objects declared with const can still be mutated. Array elements can change, and object properties can be added, modified, or removed, as long as the variable itself is not reassigned to a different array or object.

Constants are block-scoped and cannot be accessed before initialization. They follow the Temporal Dead Zone behavior that will be explored further in the dedicated Hoisting lesson.

For situations where direct object property modification should be prevented, JavaScript provides Object.freeze(). However, Object.freeze() is shallow and should not be confused with the reassignment protection provided by const.

Lesson 6 Completed
  • You understand what JavaScript constants are.
  • You know how to declare constants with const.
  • You know why const must be initialized immediately.
  • You understand why const cannot be reassigned.
  • You know the differences between const, let, and var.
  • You know when to choose const or let.
  • You understand constant naming conventions.
  • You understand const with primitive values.
  • You understand const with arrays.
  • You understand const with objects.
  • You understand the difference between reassignment and mutation.
  • You understand basic const scope behavior.
  • You understand the Temporal Dead Zone.
  • You know the difference between const and Object.freeze().
  • You are ready to learn JavaScript Data Types.
Next Lesson →

JavaScript Data Types