HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Javascript Constant

cons Keyword

In JavaScript, const is a keyword used to declare variables that are meant to remain constant throughout their lifecycle. Once a variable is declared using const and assigned a value, that value cannot be reassigned. Here are some key characteristics and usage guidelines for const:

  • The const keyword was introduced in ES6 (2015)
  • Variables defined with const cannot be Redeclared
  • Variables defined with const cannot be Reassigned
  • Variables defined with const have Block Scope

Declaration and Initialization:

Example

 
const PI = 3.14159;

Block Scope:

Like variables declared with let, const variables are block-scoped. This means they are only accessible within the block (i.e., within curly braces {}) in which they are defined.

Constant Objects and Arrays

In JavaScript, when you declare an object or an array using const, the reference to that object or array becomes constant. This means you cannot reassign the variable to point to a different object or array. However, it's important to note that the contents of the object or array can still be modified.

Here's how const behaves with objects and arrays:

Constant Objects:

Example

 
const person = { name: 'John', age: 30 };

// Modifying properties of the object is allowed
person.age = 31;
console.log(person); // Output: { name: 'John', age: 31 }

// Reassigning the variable to point to a different object is not allowed
// person = { name: 'Jane', age: 25 }; // Error: Assignment to constant variable

Constant Arrays

Example

const numbers = [1, 2, 3];

// Modifying elements of the array is allowed
numbers[0] = 10;
console.log(numbers); // Output: [10, 2, 3]

// Reassigning the variable to point to a different array is not allowed
// numbers = [4, 5, 6]; // Error: Assignment to constant variable
You can click on above box to edit the code and run again.

Output