JavaScript Arrays and const

JavaScript Tutorial

JavaScript Arrays and const

In JavaScript Arrays and const, you can declare an array using var, let, or const. Using const means the variable reference cannot be reassigned, but the contents of the array can still be modified.


 Example 1: Declaring JavaScript Arrays and const


 Modifying Array Elements

Even though the array is const, you can change its contents:

Output:

["Apple", "Orange", "Mango", "Grapes"]

 Adding and Removing Elements

Output:

["Kiwi", "Apple", "Orange", "Mango"]

 Reassigning the Array (Not Allowed)

 You cannot reassign a new array to a const variable.


 Key Points

  1. const protects the reference to the array.

  2. You can modify elements inside the array.

  3. You cannot reassign the array variable itself.


Example: Safe Usage of const Array


Summary Table:

ActionResult with const Array
Modify elementsAllowed
Add elements Allowed
Remove elementsAllowed
Reassign array Not Allowed

You may also like...