JavaScript Array push() method is used to add one or more elements at the end of an array and returns the new length.
Syntax
array.push(element1, element2,...,elementN)
Parameters
element1, element2: These are the elements you want to add to the array.
Return Value
It returns the number representing the new length of the Array.
Visual Representation
Example 1: How to Use Array push() function
This method can append a number, string, object, array, or any value to the array.
data = ['Python', 'Javascript', 'PHP']
len = data.push('Golang')
console.log('The modified array is: ', data)
console.log('The length of modified array is: ', len)
Output
The modified array is: [ 'Python', 'Javascript', 'PHP', 'Golang' ]
The length of modified array is: 4
Example 2: Add multiple elements in the Array
data = ['Python', 'Javascript', 'PHP']
len = data.push('Golang', 'C#', 'Swift')
console.log('The modified array is: ', data)
console.log('The length of modified array is: ', len)
Output
The modified array is: [ 'Python', 'Javascript', 'PHP', 'Golang', 'C#', 'Swift' ]
The length of modified array is: 6
Example 3: Appending elements of an array to another array
You can use the spread(…) operator with the push() to append elements of an array to another array.
let data = ["Python", "Javascript", "PHP"];
let numbers = [1, 2, 3, 4];
data.push(...numbers)
console.log(data)
Output
[ 'Python', 'Javascript', 'PHP', 1, 2, 3, 4 ]
You can see the elements of the numbers array are appended to the end of the data array.
Example 4: Using array-like object
let arrayLikeObject = {
0: 'Python',
1: 'Javascript',
2: 'PHP',
length: 3
};
Array.prototype.push.call(arrayLikeObject, 'Golang', 'C#');
console.log(arrayLikeObject);
Output
[ 'Python', 'Javascript', 'PHP', 'Golang', 'C#' ]
You have successfully added ‘Golang‘ and ‘C#‘ to your array-like object, and the length property has also been updated to 5.
Browser Compatibility
- Google Chrome 1
- Microsoft Edge 12
- Firefox 1
- Safari 1
- Opera 4
muavia haidry
Usefull post
thank you soo much