JavaScript push() method
The push()
method in JavaScript is used to add one or more elements to the end of an array. It modifies the original array in place and returns the new length of the array.
Syntax:
element1, element2, ..., elementN
: The elements you want to add to the array.
Return Value:
- Number: The new length of the array after the elements have been added.
Key Points:
- Mutates the original array: The
push()
method alters the original array. - Can add multiple elements: You can push multiple elements at once by passing them as separate arguments.
Example 1: Pushing one element to the array
Example 2: Pushing multiple elements at once
Example 3: Using push()
with an empty array
Performance Consideration:
- Time complexity: The time complexity of
push()
is O(1), meaning it adds elements in constant time (if no resizing of the array is required).
Summary:
push()
is used to append elements to the end of an array, modifying the original array in the process. It returns the updated length of the array and can add one or more elements in a single call.