JavaScript Array Method: push()

Java Script @ Freshers.in

JavaScript arrays are a cornerstone of web development, providing a flexible way to store and manipulate data. Among the plethora of array methods available, push() stands out as a fundamental tool for adding elements to an array dynamically. In this article, we’ll delve into push(), its syntax, purpose, and usage with detailed examples.

Understanding push()

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 addition.

Syntax:

The syntax for the push() method is simple:

array.push(element1, element2, ..., elementN)

Here, array is the array to which you want to add elements, and element1, element2, …, elementN are the elements you want to add.

Example 1: Adding Single Element

Let’s illustrate how to use push() to add a single element to an array:

let numbers = [1, 2, 3, 4];
numbers.push(5);
console.log('Modified Array:', numbers); // Output: Modified Array: [1, 2, 3, 4, 5]

In this example, the number 5 is added to the end of the numbers array using push().

Example 2: Adding Multiple Elements

You can also add multiple elements to an array in a single call to push(). Here’s how:

let fruits = ['apple', 'banana'];
fruits.push('orange', 'mango');
console.log('Modified Array:', fruits); // Output: Modified Array: ['apple', 'banana', 'orange', 'mango']

In this example, both ‘orange’ and ‘mango’ are added to the fruits array simultaneously.

Example 3: Adding Arrays as Elements

Interestingly, you can also add arrays as elements to another array using push(). Let’s see:

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
array1.push(array2);
console.log('Modified Array:', array1); // Output: Modified Array: [1, 2, 3, [4, 5, 6]]
Author: user