The Array.push()
method is a built-in JavaScript function used to add one or more elements to the end of an array. It directly modifies the original array by increasing its length and returns the new length of the array.
Syntax
arr.push(element1, element2, ..., elementN);
Parameters
(Required) The elements are to be added to the end of the array. | Description |
---|---|
element1, element2, ..., elementN | (Required) The elements to be added to the end of the array. |
Return Value
The push()
method returns the new length of the array after the elements have been added.
Example 1: Adding a Single Element
let arr = [10, 20, 30, 40, 50]; let newLength = arr.push(60); console.log(arr); // Output: [10, 20, 30, 40, 50, 60] console.log(newLength); // Output: 6
Example 2: Adding Multiple Elements
let arr = [10, 20, 30]; let newLength = arr.push(40, 50, 60); console.log(arr); // Output: [10, 20, 30, 40, 50, 60] console.log(newLength); // Output: 6
Example 3: Using push()
with an Empty Array
let arr = []; arr.push(10, 20, 30, 40); console.log(arr); // Output: [10, 20, 30, 40]
Example 4: Using push()
in a Loop
let arr = []; for (let i = 1; i <= 5; i++) { arr.push(i); } console.log(arr); // Output: [1, 2, 3, 4, 5]
Example 5: Combining Arrays with push()
– The spread operator (…) is used with push() to append all elements of one array to another.
let arr1 = [10, 20, 30]; let arr2 = [40, 50, 60]; arr1.push(...arr2); console.log(arr1); // Output: [10, 20, 30, 40, 50, 60]
Example 6: Using push()
to Manage Stacks – The push() method is perfect for implementing stack operations, where elements are added to the end.
let stack = []; // Push elements onto the stack stack.push(1); stack.push(2); stack.push(3); console.log(stack); // Output: [1, 2, 3]
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |