Table of contents
1.
Introduction
2.
What is const in JavaScript?
2.1.
Syntax of const
2.2.
Example
2.3.
Javascript
3.
Importance of const
4.
Immutability vs. Non-reassignability
4.1.
Non-reassignability
4.2.
JavaScript Code
4.3.
Immutability
4.4.
JavaScript Code
5.
Common Use Cases
5.1.
Declaring Constants
5.2.
JavaScript Code
5.3.
Configuration Objects
5.4.
JavaScript Code
5.5.
Loop Variables
5.6.
JavaScript Code
5.7.
Function References
5.8.
JavaScript Code
6.
Advanced Usage of const
6.1.
JavaScript Code
6.2.
JavaScript Code
7.
Real-world Applications of const
7.1.
Configuration Objects
7.2.
Redux Reducers
8.
Common Issues and Solutions (Extended)
8.1.
Reassignment Error
8.2.
Assignment Without Initialization
9.
Best Practices 
9.1.
When to use const
10.
Frequently Asked Questions 
10.1.
When should you use const in JavaScript?
10.2.
What is let and const in JavaScript?
10.3.
What is const in a function?
11.
Conclusion 
Last Updated: Nov 22, 2024
Easy

Const in JavaScript

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Const in JavaScript allows you to modify only the value of the array, but the reference to the array cannot be changed. The javascript const variable creates only reference to the value.

The const keyword in JavaScript is used to declare variables whose values should not be reassigned after their initial assignment.

const in javascript

 It stands for constant, indicating that the value it holds is constant post declaration. Here’s a simple example:

const pi = 3.14;

In this case, pi is a constant variable that holds the value of 3.14, and any attempt to reassign a new value to pi will result in an error.

What is const in JavaScript?

In JavaScript, const is a keyword used to declare a variable with a constant (unchangeable) value. Once a variable is assigned a value using const, that value cannot be reassigned or changed throughout the program's execution. It provides a way to create variables that are meant to be read-only.

Let's understand the core concepts of using const in JavaScript. 

Syntax of const

The const keyword is used for declaring variables that won't be reassigned to new values. The syntax is pretty straightforward but understanding its use cases is essential for effective JavaScript coding.

const variableName = value;

Here, const is the keyword.

  • variableName is the name you are giving to the variable.
     
  • value is the initial value you are assigning to the variable.
     

In JavaScript, const creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.

Example

  • Javascript

Javascript

const daysInWeek = 7;

console.log("Days in the week are: "+ daysInWeek);
You can also try this code with Online Javascript Compiler
Run Code

Explanation

In this example, daysInWeek is a constant representing the number of days in a week. The attempt to modify the value of the constant will result in an error, showcasing the immutability feature of const.

Output:

output

Importance of const

The const keyword plays a vital role in promoting good coding practices by ensuring variable non-reassignability. This characteristic is crucial for preventing bugs that could arise from accidental variable reassignment, thus making the code more predictable and easier to read and debug.

Immutability vs. Non-reassignability

These two concepts are critical and often create confusion when working with const in JavaScript.

Immutability vs. Non-reassignability

Non-reassignability

const creates a variable name identifier that cannot be reassigned to a different value. However, if the value is an object, the properties of the object can still be modified.

  • JavaScript Code

JavaScript Code

const person = {

   name: "Alice"

};

person.name = "Bob";  // This is fine

console.log(person.name); 
You can also try this code with Online Javascript Compiler
Run Code

 Output

output

person = {name: "Charlie"};  // Error: Assignment to constant variable.

In the above example, although person is a const, the name property of the object it references is mutable.

Immutability

Immutability is a broader concept. An immutable object is an object whose state cannot be modified after it is created. In JavaScript, primitive values like numbers, strings, and booleans are immutable, but objects and arrays are mutable.

const age = 30;

// age = 31;  // Error: Assignment to constant variable

  • JavaScript Code

JavaScript Code

const numbers = [1, 2, 3];

numbers.push(4);  // This is fine

console.log(numbers); 
You can also try this code with Online Javascript Compiler
Run Code

Output

output

// numbers = [1, 2, 3, 4, 5];  // Error: Assignment to constant variable

In the first scenario, age is a primitive value, and const ensures it remains assigned to 30. In the second scenario, numbers is an array, and while const prevents reassignment, it doesn't provide immutability; the array can still be modified.

These concepts underline the importance of understanding the behavior of const in different contexts. It's not just about preventing reassignment but understanding how it interacts with the data types in JavaScript. It’s a crucial part of writing predictable, bug-free code.

Common Use Cases

Declaring Constants

The const keyword is perfect for declaring constants, values that will never change over the program's execution.

  • JavaScript Code

JavaScript Code

const EARTH_RADIUS_KM = 6371;

console.log(EARTH_RADIUS_KM); 
You can also try this code with Online Javascript Compiler
Run Code

Output

output

In this scenario, the radius of the Earth is a constant value, and using const makes this clear to anyone reading the code.

Configuration Objects

Often in projects, you'll have configuration objects that shouldn't be changed after being set initially.

  • JavaScript Code

JavaScript Code

const SERVER_CONFIG = {

   HOST: 'localhost',

   PORT: 8080,

   SSL: false

};




console.log(SERVER_CONFIG); 
You can also try this code with Online Javascript Compiler
Run Code
output

Here, SERVER_CONFIG is a configuration object that holds server settings, and using const ensures that these settings aren't altered later in the code, which could introduce bugs.

Loop Variables

When working with loops, especially those iterating over fixed sets of values, const can be useful.

  • JavaScript Code

JavaScript Code

const NUMBERS = [1, 2, 3, 4, 5];

for(const number of NUMBERS) {

   console.log(number); }
You can also try this code with Online Javascript Compiler
Run Code

 Output

output

In this example, using const for the loop variable number makes it clear that number should not and cannot be reassigned within the loop body.

Function References

When you have function references that you do not intend to reassign, const is a good choice.

  • JavaScript Code

JavaScript Code

const computeArea = function(radius) {

   return Math.PI * radius * radius;

};




console.log(computeArea(10)); 
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Here, the computeArea function reference is declared with const, indicating that it should not be reassigned later in the program.

Advanced Usage of const

const with Object.freeze():

The const keyword in JavaScript ensures that the identifier cannot be reassigned. However, if the identifier refers to an object, the properties of that object can still be modified. In contrast, Object.freeze() is a method that prevents the modification of existing properties values and the addition of new properties to an object.

Combining these two can create a pattern of deeper immutability:

  • JavaScript Code

JavaScript Code

const person = Object.freeze({

   name: "Alice",

   age: 30

});




person.name = "Bob";  // This will fail silently or throw an error in strict mode

console.log(person.name);
You can also try this code with Online Javascript Compiler
Run Code

Output 

output

// Trying to add new properties will also fail

  • JavaScript Code

JavaScript Code

person.gender = 'female';  // This will fail silently or throw an error in strict mode

console.log(person.gender); 
You can also try this code with Online Javascript Compiler
Run Code

Output

output

In the above code snippet, the person object is both a constant and frozen, which prevents any modification to the object. This can be especially useful in situations where data integrity is crucial, such as configuration data.

Real-world Applications of const

Configuration Objects

Projects often require certain configurations to be set and unchanged throughout the runtime of the application. Utilizing const for this purpose can ensure these configurations remain intact.

const config = {
    apiUrl: 'https://api.example.com',
    port: 3000
};

 

// Usage

fetch(config.apiUrl + '/endpoint')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

 

In the above snippet, config is an object holding configuration data that is used in a fetch request. This setup ensures that the configurations are read-only, promoting consistency throughout the application.

Redux Reducers

Redux, a popular state management library in JavaScript applications, often employs const for defining action types, which are crucial for the reducer functions to understand the actions to be performed.

const ADD_ITEM = 'ADD_ITEM';
const REMOVE_ITEM = 'REMOVE_ITEM';


function todoReducer(state = [], action) {
    switch(action.type) {
        case ADD_ITEM:
            return [...state, action.item];
        case REMOVE_ITEM:
            return state.filter(item => item.id !== action.id);
        default:
            return state;
    }
}

 

// Dispatching actions

store.dispatch({ type: ADD_ITEM, item: { id: 1, text: 'Learn Redux' } });

In this expanded example, action types ADD_ITEM and REMOVE_ITEM are defined using const, ensuring they remain unmodified. The todoReducer function then uses these constants to understand the action types and modify the state accordingly.

Common Issues and Solutions (Extended)

Reassignment Error

One of the most common errors when using const is attempting to reassign its value after declaration. The following code snippet demonstrates this error:

const number = 42;

number = 50;  // Uncaught TypeError: Assignment to constant variable.

Solution: To avoid this error, use let if you anticipate the need to reassign the variable in future:

let number = 42;

number = 50;  // No error, the variable is reassigned successfully

Assignment Without Initialization

Unlike var and let, const requires an initializer. A const declaration without initialization will result in a syntax error:

const number;  // Uncaught SyntaxError: Missing initializer in const declaration

Solution: Always provide an initial value when declaring a const variable:

const number = 42;  // No error

Best Practices 

When to use const

Immutable Values: Use const for values that should remain unchanged throughout the program execution. This signifies the intent that the value should not be modified, making the code more readable and predictable.

const PI = 3.14159;

Object References: When working with objects, using const ensures that the reference to the object remains constant. This is useful in scenarios where the reference should remain intact, but the object's properties may be modified.

const config = {
  apiEndpoint: 'https://api.example.com'
};

 

// Modifying properties is okay

config.apiEndpoint = 'https://api-new.example.com';  // No error

 

// Reassigning the reference is not allowed

config = { apiEndpoint: 'https://api-2.example.com' };  // Uncaught TypeError: Assignment to constant variable.

Frequently Asked Questions 

When should you use const in JavaScript?

Use const for variables whose value should not be reassigned. It ensures immutability for primitive values and prevents reference reassignment for objects.

What is let and const in JavaScript?

let is used for block-scoped, reassignable variables, while const declares block-scoped variables whose value or reference cannot be reassigned.

What is const in a function?

const in a function ensures that the variable defined cannot be reassigned within the function, often used for constants or references.

Conclusion 

We delved deep into the const keyword, exploring its syntax, usage scenarios, and its role in maintaining data integrity in JavaScript applications. Through examples, we demonstrated common issues and provided solutions to ensure smooth development experience. We also discussed best practices, ensuring a clear understanding of when and how to use const effectively in different scenarios. This exploration sheds light on the importance of const in promoting good coding practices and creating reliable, maintainable JavaScript code.

You can refer to our guided paths on the Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass