Open In App

What does Const Do in JavaScript ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, the const keyword is used to declare a constant variable, meaning its value cannot be reassigned or redeclared. However, it does not make the variable immutable; that is, it does not prevent changes to the properties or elements of the variable’s value. Also, const does not support hoisting means we can not access const before declaration.

These are the following ways to use const:

Declaring a Constant Variable

The const keyword in JavaScript is primarily used for declaring constants. The value of a const variable cannot be reassigned after initialization.

Example: This example shows the declaration of some constant by using the const keyword.

Javascript




const PI = 3.14159;
console.log(PI); // Output: 3.14159
// Attempting to reassign the value of a
// const variable will result in an error
// PI = 3.14; // Error: Assignment to constant variable.


Output

3.14159

Using const with the Object Literal

const keyword in JavaScript is primarily used for declaring constants. The value of a const variable cannot be reassigned after initialization.

Example: This example shows the declaration of an object by using the const keyword so that it can not changed in the future.

Javascript




const person = {
    name: "geek",
    age: 30
};
console.log(person.name);
// Modifying the properties of a const object is allowed
person.age = 31;
console.log(person.age);


Output

geek
31

Using const with Arrays

const variables must be initialized at the time of declaration. const variables have block scope like let.

Example: This example shows the declaration of array using const keyword.

Javascript




const numbers = [1, 2, 3];
console.log(numbers[0]);
// Modifying the elements of a const array is allowed
numbers.push(4);
console.log(numbers);


Output

1
[ 1, 2, 3, 4 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads