Skip to main content

JavaScript const Keyword

By SamK
0
0 recommends
Topic(s)

In this tutorial, you will learn about the const keyword, which is used to declare variables in JavaScript,

With const, the value of a variable cannot be reassigned once it is set.

const x = 10;
x = 20;  // Error: Assignment to constant variable.

A variable declared with const must be assigned a value at the time of declaration.

const x = 3;
console.log(x); // Output: 3

When to Use?

Use const in JavaScript when you are certain that the variable's value should remain constant and not be reassigned.

You should use const when declaring a new array, object, function, or a regular expression (RegExp).

Constant Objects and Arrays

The const keyword creates a constant reference to a value, but it doesn't make the value itself immutable.

What you cannot do with const:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

What you can do with const:

  • Modify the elements of a constant array
  • Change the properties of a constant object

Constant Arrays

You can modify the elements of a constant array:

// Create an Array:
const fruits = ["Apple", "Banana", "Cherry"];

// Change an element:
fruits[0] = "Mango";

// Add an element:
fruits.push("Orange");

// Display the Array:
console.log(fruits); // Output: Mango,Banana,Cherry,Orange

But you cannot reassign the array:

try {
 const fruits = ["Apple", "Banana", "Cherry"];
 fruits = ["Mango", "Orange", "Pineapple"]; // This will throw an error
} 
catch (err) {
 console.log(err.message);
}
// Error output: Assignment to constant variable.

Constant Objects

You can modify the properties of a constant object:

// Create an object:
const fruit = { name: "Apple", color: "green", taste: "sweet" };

// Change a property:
fruit.color = "red";

// Add a property:
fruit.season = "Autumn";

console.log(fruit.season); // Output: Autumn

But you can NOT reassign the object:

try {
    const fruit = { name: "Apple", color: "green", taste: "sweet" };
    fruit = { name: "Mango", color: "yellow", taste: "tropical" }; 
} 
catch (err) {
    console.log(err.message); // Error output: Assignment to constant variable.
}

Block Scope

Declaring a variable with const behaves similarly to let in terms of block scope.

The y declared within the block in the following example is entirely separate from the y declared outside the block.

const y = 20;
// Here y is 20

{  
const y = 5;
// Here y is 5
}

// Here y is 20
console.log(y); // Output: 20

Redeclaring

Redeclaring an existing var or let variable to const in the same scope will result in an error because const variables must be unique and cannot share the same name within the same block or function scope.

let x = 10;  
const x = 20; // This will throw an error  
var y = 15;  
const y = 25; // This will also throw an error  

Reassigning an existing const variable within the same scope is not allowed because const variables are immutable in terms of reassignment. Once declared, the variable cannot be assigned a new value.

const x = 10;  
x = 20; // This will throw an error

Redeclaring a variable with const in another scope or block is allowed because const variables are block-scoped.

{
  const x = 10;  
  console.log("x is " + x); // Output: x is 10
}

{
  const x = 20;  
  console.log("x is " + x); // Output: x is 20
}

// Each `x` exists in its own block scope, so no conflict occurs.

Hoisting

Variables defined with const are hoisted to the top of their block like let variables, but they are not initialized. Attempting to access or use a const variable before its declaration will result in a ReferenceError.

try {
 alert(fruitName);
 const fruitName = "Apple";
} catch (err) {
 console.log(err.message); // Error output: Cannot access 'fruitName' before initialization
}

Questions & Answers