The following example shows how to use the Array.push() method to add an element to an array:
const fruits = ['peach', 'mango', 'banana']; fruits.push('strawberry'); console.log(fruits); // Expected output: // ["peach", "mango", "banana", "strawberry"]
In the above example, the fruits array initially contains 3 items (defined in the first line of code). The push() method is used to add a fourth item – strawberry – to the fruits array. This item is added at the end of the array as its last item.
The syntax of the push() method is as follows:
arrName.push(element1, element2… elementN)
This method accepts multiple items to add, as the example below demonstrates:
fruits.push('apple', 'pear'); console.log(fruits); // Expected output: // ["peach", "mango", "banana", "strawberry", "apple", "pear"]
In the above example, two additional items are added to the end of the fruits array: apple and pear. Both items are pushed onto the end of the provided array in the order in which they appear – first “apple”, then “pear”. The two new elements appear at the end of the fruits array.
The push() method returns the length of the new array after the items have been added:
const nums = [1, 2, 3, 4, 5]; const newLength = nums.push(6); console.log(nums); // Expected output: [1, 2, 3, 4, 5, 6] console.log(newLength); // Expected output: 6
In the example above, the number 6 is added to the nums array by applying the push() method. The return value of push() is stored in const newLength. As the above code shows, the new length of the array (i.e. the number of items it contains) is 6 after the addition of the final element.
Related Articles
JavaScript – How to Use the includes() Method