JavaScript Array Const
ECMAScript 2015 (ES6)
In 2015, JavaScript added a significant new term: const
.
Using const
is now a usual way to create arrays.
Cannot be Reassigned
An array created using the const
keyword can't be changed once it's defined.
Arrays are Not Constants
The keyword const
is a little misleading.
This doesn't create a fixed array. Instead, it establishes a permanent link to an array.
Due to this, it's still possible to modify the elements of an unchanging array.
Elements Can be Reassigned
You can change the elements of a constant array:
Assigned when Declared
In JavaScript, when you use the const
keyword to create a variable, you have to give it a value right at the moment when you declare it.
Explanation: When you create an array using const
you need to set its initial values right when you declare it.
Using const
without initializing the array is a syntax
error:
Example
This will not work:
const cars;
cars = ["Saab", "Volvo", "BMW"];
Arrays created using the var
keyword can be given values whenever you want.
You can even use the array before it is declared:
Const Block Scope
An array created with the const
keyword has a scope that is limited to the block of code it's defined in.
An array declared in a block is not the same as an array declared outside the block:
An array created using the var
keyword does not have block scope.
Find additional information on Block Scope in the chapter titled JavaScript Scope.
Redeclaring Arrays
You can use the same array name anywhere in your program if you initially declared it with var
.
Example
var cars = ["Volvo", "BMW"]; // Allowed
var cars = ["Toyota", "BMW"]; // Allowed
cars = ["Volvo", "Saab"]; // Allowed
You cannot use the same name for an array when you've already declared it with const
in the same part of your code.
Example
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
{
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
}
Redeclaring or reassigning an existing const
array, in the same scope, or in
the same block, is not allowed:
Example
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
}
Reusing an array using const
in a different part of the code or within a new section is acceptable.
Example
const cars = ["Volvo", "BMW"]; // Allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
}
{
const cars = ["Volvo", "BMW"]; // Allowed
}