Home » Linux » Javascript Push Add Item To Array

How to Add one or More Items to an Array In JavaScript with push()

This tutorial will show you how to add items to a JavaScript array with the push() method – with code examples.

You don’t want to have to re-declare an array every time you want to change the values in it – so let’s look at how to add items to existing arrays using the push() method.

About JavaScript Arrays and Declaring Arrays

I’ve covered the best way to declare Arrays in JavaScript in our article here.

JavaScript Array push() Method Syntax

method is a function or procedure attached to an object. Calling that object’s method will perform that procedure on that object.

The push() method is built-in to the JavaScript array object and available to every array, allowing items to be appended to the array.

The syntax is as follows:

array.push(VALUES)

Note that:

  • array can be any array variable
  • VALUES is a list of one or more comma-separated values to be added as items in the array
    • They can be of any type

Adding Single Items to an Array using push()

Below, an array is declared, and a single value is appended using the push() method:

var fruitArray = ['apple, 'banana', 'grape']; // Declare an array with some fruit

fruitArray.push('orange'); // Append a single value to the array by calling the array's push method

The value of fruitArray is now:

['apple, 'banana', 'grape', 'orange']

Adding Multiple Items to an Array using push()

Below, an array is declared, and then multiple values are appended using the push() method:

var fruitArray = ['apple, 'banana', 'grape']; // Declare an array with some fruit

fruitArray.push('orange', 'watermelon', 'lemon'); // Append multiple values to the array by calling the array's push method and supplying a comma-separated list of values

The value of fruitArray is now:

['apple, 'banana', 'grape', 'orange', 'watermelon', 'lemon']

Other Things to Do With JavaScript Arrays

We’ve got a bunch of other articles about JavaScript arrays – check them out here.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment