Javascript Array Push method in detail

    Jun 10, 2018       by Pankaj Kumar
array-push.jpg

In this article, I am going to dive in the array push method in javascript.  The array push() method adds a new element at the end of the array and returns the array with new length. For adding a new element at the beginning unshift() method is used.

 

Arrays are just regular Objects

In Javascript, there are mainly 6 data types - the primitives(number, string, boolean, null, undefined) and object (the reference type).  Arrays do not belong to the list because they are objects as well.

The array items are nothing more than property of that object. We can use any name as property for an object, also numbers. At some case, if the property name is not a valid identifier, We can access it through obj[property].

Let's understand the same with below example:

 

 
var obj = {
0: 'apple',
1: 'orange',
'color': 'red',
'': 'having blank key'
};
 
console.log(obj[0], obj[1], obj['color'], obj['']);
 

 

Declaring an Array

Below are the ways by which we can create an array in javascript.

using literal

var newArr = [1,2,3,4]

 

Using constructor

var newArray = new Array(1,2,3,4);

 

Declaring array using literal is the best way. the Array declared using constructor behaves differently if its only argument is a number.

 

Javascript Array Push Method

Have a look on the syntax below:

myArr.push(element1)

 

The above command adds the new element to the array at last position. This method is intentionally generic. This method can also be used with call() and apply().

 

Adding elements to an Array

 

 
let fruits = ['mango', 'orange'];
let fruits2 = fruits.push('apple');
 
console.log(fruits2); // will print ["mango", "orange", "apple"]
 

 

Merging two arrays

 

 
let fruits = ['apple', 'mango'];
const newFruits = ['banana', 'orange'];
 
Array.prototype.push.apply(fruits, newFruits);
 
console.log(fruits); // will output ["apple", "mango", "banana", "orange"]
 

 

Do not use the apply(),  if the second array (newFruits in the example) is vast because the max number of arguments that one function can handle is limited in practice.

So, apply() will add the second array into the first array and we can see the combined array by returning the original array in our case it is fruits.

 

Add Multiple items in an Array

 

 
let fruits = ['apple', 'banana'];
 
fruits.push('mango', 'orange');
 
console.log(fruits); // will output ["apple", "banana", "mango", "orange"]
 

 

That’s all for now. Thank you for reading and I hope this post will be very helpful for understanding the javascript Array push method.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


Find other similar Articles here: