What does Const Do in JavaScript ?
Last Updated :
14 Feb, 2024
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);
|
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);
person.age = 31;
console.log(person.age);
|
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]);
numbers.push(4);
console.log(numbers);
|
Share your thoughts in the comments
Please Login to comment...