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.
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:
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.
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().
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.
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.