Array Basics
Arrays stores ordered lists of data.
Array declaration
Arrays can be declared in several ways. Most used methods are:
Method 1
// Using Array constructor
var arr = new Array(); // Create an empty array
var arr1 = new Array(5); // Create an empty array of length 5
var arr2 = new Array("Black", "White", "Red"); // Create an empty array with following elements
console.log(arr);
console.log(arr1);
console.log(arr2);
Array()
constructor is used to create an array object.
Method 2
var arr = []; // Creates an empty array
var arr1 = [, , , , ,]; // Creates an empty array of length 5
var arr2 = ["Car", "Bike", "Cycle"]; // Creates an array with the following elements
var arr3 = [1, , , 4, , 6]; // Creates an array of length 6 with empty space as undefined
console.log(arr);
console.log(arr1);
console.log(arr2);
console.log(arr3);
The following declarations are equivalent to the declarations in method 1. In arr1
an array of length 5 is created.
In which the interpreter treats it as five undefined values. Each comma represents each element in the array if all elements are undefined.
But using the comma in such cases can cause confusions. Thus, this method of declaration is not widely used.
Other methods are
var x = 2,
y = 3,
z = 4;
var arr = [x, y, z];
console.log(arr);
Add, change or remove array elements
Add element
var arr = [];
arr[0] = 2;
arr[1] = 3;
arr[2] = 4;
console.log(arr);
By accessing the array index we can manipulate the array element.
Change element
var arr = [1, 2, 3, 4];
arr[0] = 2;
console.log(arr);
Remove element
var arr = [1, 2, 3, 4];
delete arr[0], arr[1];
console.log(arr);
While using delete
the element gets removed from the array, but the length of the array remains the same and also you cannot
delete multiple elements in a single line.