If we have an array that once had a number of items, but now we have to add one extra element to the array. The javascript array append will help you to add that extra element at the end of the array instead of creating a new array.
JavaScript Array push
The Array.prototype.push() function helps you to add new elements at the end of the array and returns with the new length of the array. javascript array append helps to apply one or multiple elements in the array.
Syntax for javascript array append
It can be used for arrays holding strings, variables, or functions. Syntax for javascript array append another array
array.push(" element1, element2, element3,., elementN,").
Parameter for javascript array push:
element1, element2, element3,., elementN: Elements to be added to array
Returns value for javascript array push
Push in javaScript returns new length of array.
Examples :
Here are some examples of javascript array append.
Example 1:
In this example, we will learn to add one element using the javascript array push().
const pets = ['dogs', 'cats'];
pets.push('chinchillas');
console.log(pets);
In this example, we have added only one extra element, i.e. chinchillas
Result:
[ ‘dogs’, ‘cats’, ‘chinchillas’ ]: The push() returns with an extra element.
Example 2:
In this example, we will learn to add more than one element using the javascript array push().
const pets= ["dogs", "cats"];
pets.push("chinchillas", "pigs", "birds");
console.log(pets);
In this example, we have added more than one extra element, i.e. “chinchillas”, “pigs”, “birds”.
Result
[ ‘dogs’, ‘cats’, ‘chinchillas’, ‘pigs’, ‘birds’ ]: The push() returns with extras element added.