An array declared with const
follows block scope rules.
Therefore, an array declared within a block behaves differently from one declared outside the block.
Example
const cars = [“Saab”, “Volvo”, “BMW”]; // Here cars[0] is “Saab” { const cars = [“Toyota”, “Volvo”, “BMW”]; // Here cars[0] is “Toyota” } // Here cars[0] is “Saab” |
An array declared with ‘var
‘ does not adhere to block scope rules.
Example
var cars = [“Saab”, “Volvo”, “BMW”]; // Here cars[0] is “Saab” { var cars = [“Toyota”, “Volvo”, “BMW”]; // Here cars[0] is “Toyota” } // Here cars[0] is “Toyota” |
You can redeclare an array that was initially declared with ‘var
‘ anywhere in a program.
Example
var cars = [“Volvo”, “BMW”]; // Allowed var cars = [“Toyota”, “BMW”]; // Allowed cars = [“Volvo”, “Saab”]; // Allowed |
It’s not permitted to redeclare or reassign an array to a constant (const
) in the same scope or block.
Example
var cars = [“Volvo”, “BMW”]; // Allowed const cars = [“Volvo”, “BMW”]; // Not allowed { var cars = [“Volvo”, “BMW”]; // Allowed const cars = [“Volvo”, “BMW”]; // Not allowed } |
It’s not allowed to redeclare or reassign an existing constant array (const
) in the same scope or block.
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 } |
Redeclaring an array with ‘const
‘ in another scope or block is allowed.
Example
const cars = [“Volvo”, “BMW”]; // Allowed { const cars = [“Volvo”, “BMW”]; // Allowed } { const cars = [“Volvo”, “BMW”]; // Allowed } |