Array Operations in JavaScript
In the previous lesson, we discussed that string operations are defined by string methods. Similar is the case for JavaScript arrays. Their operations are also defined using array methods.
The most basic operation of arrays is to add new elements to arrays. Elements can be added to an array using the .push()
method, where the element to be added is enclosed in the parenthesis. The element will always be inserted at the end of the list. An example code is given below.
1var fruits = ["apple", "orange", "grapes"];
2fruits.push("strawberry");
3
4console.log(fruits); // prints ["apple", "orange", "grapes", "strawberry"]

To remove elements from a list, JavaScript has two methods. .pop()
directly removes the last element from the array. .splice()
removes the elements in the array by specifying the index of the element to be removed and the count of elements to be removed. For example,
1var fruits = ["apple", "orange", "grapes", "strawberry"];
2fruits.pop();
3console.log(fruits); // prints ["apple", "orange", "grapes"]
4
5fruits.splice(1, 1); // removes element at index 1, once
6console.log(fruits); // prints ["apple", "grapes"]

For the length of the array, JavaScript does not have a built-in method. Instead, the length of the array is accessed by an array property length
.
1var fruits = ["apple", "orange", "grapes"]
2console.log(fruits.length); // 3
A summary of the list methods discussed for JavaScript is listed in the table below.
Method | Usage |
---|---|
push() | Insert a new element at the end of array |
pop() | Removing the last element from the array |
splice() | Remove the element and number of elements in an array using the index of element |
A comprehensive list of all JavaScript array methods is available here.