JavaScript(JS) array method - push
The push()
method is a built-in JavaScript array method that adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array.
Here's an example of how to use the push()
method:
let numbers = [1, 2, 3, 4]; let newLength = numbers.push(5, 6); console.log(numbers); // [1, 2, 3, 4, 5, 6] console.log(newLength); // 6
In this example, we have an array numbers
containing the elements [1, 2, 3, 4]
. We use the push()
method to add two new elements (5
and 6
) to the end of the numbers
array, and store the new length of the array (which is 6
) in the variable newLength
. The push()
method modifies the original numbers
array by adding the two new elements (5
and 6
) to the end of the array. We then log the modified numbers
array and the new length (6
) to the console.
Note that you can also use the push()
method to add a single element to an array:
let numbers = [1, 2, 3]; numbers.push(4); console.log(numbers); // [1, 2, 3, 4]
In this example, we add a single element (4
) to the end of the numbers
array using the push()
method. The modified numbers
array is then logged to the console.