Skip to content
the poor coder

javascript array push

Poor Man
Published
Reading time
1 min read
On this page

Javascript Array Push#

The push() method in JavaScript is used to add one or more elements to the end of an array and returns the new length of the array.

Syntax:#

Text

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

Here, arr is the array on which the push operation is being performed, and element1, element2, ..., elementN are the elements that need to be added to the end of the array.

The push method modifies the original array and returns the new length of the array.

Example:#

Text

let myArray = ['apple', 'banana', 'orange'];
let length = myArray.push('grapes');

console.log(myArray); // Output: ['apple', 'banana', 'orange', 'grapes']
console.log(length); // Output: 4
  

The above code adds a new element 'grapes' to the end of the myArray, and then logs the new array and its length.

Multiple Ways:#

  • We can also use the spread operator to add elements to an array:
Text

let myArray = ['apple', 'banana', 'orange'];
myArray = [...myArray, 'grapes'];

console.log(myArray); // Output: ['apple', 'banana', 'orange', 'grapes']
    
  • Another way to add elements to an array is by using the concat() method:
Text

let myArray = ['apple', 'banana', 'orange'];
let newArray = myArray.concat(['grapes']);

console.log(myArray); // Output: ['apple', 'banana', 'orange']
console.log(newArray); // Output: ['apple', 'banana', 'orange', 'grapes']
    

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC