Const Arrays¶
It is a common practice to declare arrays with the const keyword.
1. Cannot be Reassigned¶
An array declared with const cannot be reassigned:
2. Elements CAN be Changed¶
It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array:
3. Block Scope¶
An array declared with const has Block Scope.
const cars = ["Saab", "Volvo", "BMW"];
{
const cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Saab"
Always use Const
Unless you intend to reassign the entire array variable to a completely new array, always use const for arrays and objects.