Declaring and Mutating Arrays
Explore how to declare JavaScript arrays with or without initial elements, access items by index, and understand array mutability. Discover practical ways to copy arrays using slice, spread, and Array.from to prevent unintentional shared references.
We'll cover the following...
Declaration
Arrays are declared in various ways. Let’s examine the syntax so one by one.
Declaring empty arrays
An empty array can be declared in three ways in JavaScript. The code below shows the syntax.
In the code above, we create an empty array on lines 1 and 2. Passing one number to Array() creates an empty array the size of that number.
Declaring arrays with elements
Now, create arrays with some elements.
In both above methods, we create two arrays on lines 1 and 2 of multiple elements. There is no restriction on types of values we can add within the array. Passing multiple values to Array just populates the array with those values. ...