In JavaScript, the push() method is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.
Syntax:
array.push(element1, element2, ..., elementN)
- array: The array to which elements will be added.
- element1, element2, ..., elementN: Elements to be added to the end of the array.
Example:
let fruits = ['apple', 'banana'];
let newLength = fruits.push('orange', 'grape');
console.log(newLength); // Output: 4
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grape']
Explanation:
- In the example, push('orange', 'grape') adds the elements 'orange' and 'grape' to the end of the fruits array.
- The push() method modifies the original array ('fruits') by adding the new elements to it.
- The method returns the new length of the array after the elements have been added.
The push() method provides a convenient way to add elements to the end of an array, making it useful for dynamic data manipulation in JavaScript.