The push()
method in JavaScript 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 after the elements have been added.
Syntax:
array.push(element1, element2, ..., elementN)
Parameters:
- element1, element2, …, elementN: These are the elements to be added to the array. You can add multiple elements at once.
Return Value:
- The method returns the new length of the array after the elements have been added.
Example 1: Adding a single element
let fruits = ["apple", "banana"];
let newLength = fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
console.log(newLength); // 3
Example 2: Adding multiple elements
let numbers = [1, 2, 3];
let newLength = numbers.push(4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(newLength); // 5
Example 3: Adding different types of elements
let mixedArray = [42, "hello"];
mixedArray.push(true, null, {key: "value"});
console.log(mixedArray); // [42, "hello", true, null, {key: "value"}]
The push()
method is commonly used for dynamically adding elements to an array, and since it changes the array in place, it’s very useful in scenarios like growing an array in response to user actions or data inputs.