Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason JavaScript developers don't use Array.push()?

Tags:

javascript

I commonly see developers use an expression like the following in JavaScript:

arr = [] arr[arr.length] = "Something" arr[arr.length] = "Another thing" 

Wouldn't push be more appropriate?

arr = [] arr.push("Something") arr.push("Another thing") 
like image 329
bloudermilk Avatar asked Mar 27 '13 00:03

bloudermilk


People also ask

What can I use instead of push in JavaScript?

Alternatives of push() method in JavaScript Approach 1: Use the length property to insert the element at the end of the array. Example: This example implements the above approach.

Can you push objects into an array JavaScript?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.

What does array push do in JavaScript?

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Does push change original array JavaScript?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements.


1 Answers

I actually asked myself the same question at the start of this year. UPDATED with new test cases http://jsperf.com/array-push-vs-unshift-vs-direct-assignment/2

It appears that push is much faster in chrome, and about equal in FF. Also direct is faster in IE9, but I would be interested to see how it performs in IE10.

I would say that most developers would assume setting the length of the array, and then using direct assignment is faster, as is the case with most programming languages. But JavaScript is different. Javascript arrays aren't really arrays, they're just key/value maps just like all other JavaScript objects. So the pre-allocation is essentially falling on deaf ears.

Personally I prefer push (:

like image 197
gkiely Avatar answered Oct 05 '22 23:10

gkiely