push() in JavaScript – Add Items to End of Array
Whenever you use push() on an array, the method does the following:
- It adds its arguments to the end of its calling array.
- It returns the calling array’s new length.
Syntax of the push()
Method
push()
accepts one or more arguments. Here is the syntax:
The item1, item2, ..., itemX
arguments represent the items you wish to add to the end of the calling array.
Let’s see precisely how push()
works with some examples.
Example 1: Use push()
to Add One New Item to the End of an Array
The snippet above used push()
to append an item (5
) to the end of the calling array.
Let’s consider another example.
Example 2: Use push()
to Add Three New Items to the End of an Array
In the snippet above, the totalFruits
’ invocation returned 5
because push()
returned the calling array’s new length.
Keep in mind that you can also use JavaScript’s length
property to add new items to the end of an array object. Let’s discuss how below.
How to Use JavaScript’s length
Property to Add Items to the End of an Array Object
You can use JavaScript’s length
property to append a new item to the end of an array like so:
In the snippet above, we used the length
property to specify the index position we wish to insert the new item (30
).
In other words, since numbersArray.length
will return the number of items currently in the calling array, numbersArray[numbersArray.length]
is equivalent to numbersArray[4]
.
Therefore, the numbersArray[numbersArray.length] = 30
code tells the computer to place 30
at numbersArray
’s fourth index position.
So, what exactly is the difference between the length
property and the push()
method. Let’s find out.
push()
vs. length
: What’s the Difference Between the Two Ways of Adding Items to the End of an Array?
JavaScript’s length
property can add only a single item per time into an array object. However, push()
can add multiple items.
Here’s an example:
Notice that push()
permits adding multiple values to an array. However, length allows only a single item per time.