But what if you need to store the state or city names of a country in variables, and this time there are more than three? It is difficult and tedious to save each of them in a distinct variable. Using so many variables at the same time and keeping track of them all will be a challenging effort. And here is where the array comes into play. Arrays solve this problem by storing multiple values or groups of values in an ordered structure.
Creating an Array
Accessing the Elements of an Array
The square bracket syntax can be used to access array items by index. An index is an integer that represents the location of an element in an array. Array indexes start at zero. This implies that the first item in an array is kept at index 0 rather than index 1, the second item at index 1, and so on. Array indices begin at 0 and increase to the number of items minus one. As a result, an array of five components would have indices ranging from 0 to 4.
Getting the Length of an Array
The length property of an array returns the total number of elements present in the array. The length of an array is always bigger than the index of any of its elements.
Looping Through Array Elements
The for loop may be used to access each element of an array in sequential order. The for-of loop, introduced in ECMAScript 6, is a simpler way to iterate through array elements. You do not need to initialise or maintain track of the loop counter variable in this loop (i).
Adding New Elements to an Array
- Use the push() function to add a new element to the end of an array.
- Similarly, use the unshift() function to insert a new element at the beginning of an array.
- You can also use the push() and unshift() methods to add multiple elements at once.
Removing Elements from an Array
The pop() function may be used to remove the final entry from an array. The value that was popped out is returned by this procedure. Similarly, the shift() function may be used to delete the first entry from an array. This function also returns the shifted out value.