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")
I commonly see developers use an expression like the following in JavaScript:
Wouldn't
|
|||
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 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 |
|||||||||||||
|
It's all about performance - but it does not really matters I guess http://www.scottlogic.co.uk/2010/10/javascript-array-performance/ |
|||||||||||||
|
I believe that it's mostly habit. Some developers use it simply because it's the way they are used to do it, and haven't considered that Some developers have learned once upon a time that one method is much faster than another, and haven't reviewed this in light of the recent performance improvements of the Javascript engines. Personally I use |
|||||
|
It's a way to limit nested braclets. If you have enough of them you cant see howmany there are or howmany you need (when later looking at the code). I would use a var, one should only have to count things one time.
|
|||
|
Very often when I'm pushing an object into an array, I want the reference to that object to be returned to me. For example:
Now I have the new object and I've added it to an array. If I'd used push then I would have been returned the length of the array. It would look like the following:
or even uglier, especially if the object gets big:
Personally, I love functions with immediate return statements. Keeps it simple and easy to look at. Love the question. Thanks for asking it. |
|||
|
push()
, and now I feel like I'm missing some hitherto secret contraindication for such usage... – David Thomas Mar 27 '13 at 0:27for
loop). – Tim Medora Mar 27 '13 at 0:28