...

/

Declaring and Mutating Arrays

Declaring and Mutating Arrays

Overview of how arrays are declared and mutated in JavaScript.

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.

Press + to interact
var arr = new Array(); // Assign arr an empty array object
var arr2 = []; // Assign an empty array to arr2
var arr3 = new Array(12) // Assign an array of 12 size to arr3
console.log(arr, arr2, arr3) // Print array

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.

Press + to interact
var arr1 = new Array(1, -2, "3"); // Create an array object and assign to arr1
var arr2 = [4, 5, "6", true]; // Create an array object and assign to arr2
console.log(arr1,arr2)

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. ...