An array is a special variable, which can hold more than one value at a time.
An array can hold a number of values under a single name and the values can be accessed using an index number.
Javascript arrays are zero-indexed meaning the first element of an array is at index 0 and the index value of last element is array's length property minus 1.
You can create an array as below:
const arr1 = ['item1', 'item2', 'item3']
OR
let arr2 = ['item1', 'item2', 'item3']
Array elements can be accessed with the help of index value of the element. The index value starts from 0 (first element is at index 0).
You can access an elemene with the syntax:
variableName[indexValue]
arr1[0] = item1
arr1[1] = item2
arr1[2] = item3
And you can update the complete array as:
const alpha = ['a', 'b', 'c']
alpha = ['d', 'e']
console.log(alpha) //['d', 'e']
Also you can update array elements as:
const alpha = ['a', 'b', 'c']
alpha[0] = 'e'
console.log(alpha) //['e'. 'b'. 'c']
If an array is nested inside another array, it is called a nested array.
The element of a nested array can be accessed as
arr[i][j] where i is the index of nested array and j is the index of element inside the nested array
You can find the length of an array with the length property.
Suppose for an array
const arr = [1, 2, 3]
console.log(arr.length) //3
Some simple methods to manipulate an array
You can add an element at the end of an array using push method.
arrayVariable.push(elementToAdd)
It removes the first item of the array.
It adds the element as the first item in the array.
It takes two variables.
arr.slice([start, end])
Slices the array from the start index to end one with the ending not included.
If start is undefined, slice starts from 0 index.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.