Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the push method or .length when adding to array?

Tags:

javascript

What are the downsides to doing:

var myArray = [];
myArray[myArray.length] = val1;
myArray[myArray.length] = val2;

instead of:

var myArray = [];
myArray.push(val1);
myArray.push(val2);

I'm sure the push method is much more "acceptable", but are there any differences in functionality?

like image 406
mowwwalker Avatar asked Jul 21 '11 07:07

mowwwalker


1 Answers

In JS there are 3 different ways you can add an element to the end of an array. All three have their different use cases.

1) a.push(v), a.push(v1,v2,v3), a.push(...[1,2,3,4]), a.push(..."test")

Push is not a very well thought function in JS. It returns the length of the resulting array. How silly. So you can never chain push() in functional programming unless you want to return the length at the very end. It should have returned a reference to the object it's called upon. I mean then it would still be possible to get the length if needed like a.push(..."idiot").length. Forget about push if you have intentions to do something functional.

2) a[a.length] = "something"

This is the biggest rival of a.push("something"). People fight over this. To me the only two differences are that

  • This one returns the value added to the end of the array
  • Only accepts single value. It's not as clever as push.

You shall use it if the returned value is of use to you.

3. a.concat(v), a.concat(v1,v2,v3), a.concat(...[1,2,3,4]), a.concat([1,2,3,4])

Concat is unbelievably handy. You can use it exactly like push. If you pass the arguments in array it will spread them to the end of the array it's called upon. If you pass them as separate arguments it will still do the same like a = a.concat([1,2,3],4,5,6); //returns [1, 2, 3, 4, 5, 6] However don't do this.. not so reliable. It's better to pass all arguments in an array literal.

Best thing with concat is it will return a reference to the resulting array. So it's perfect to use it in functional programming and chaining.

Array.prototype.concat() is my preference.

4) A new push() proposal

Actually one other thing you can do is to overwrite the Array.prototype.push() function like;

Array.prototype.push = function(...args) {
                         return args.reduce(function(p,c) {
                                              p[p.length] = c;
                                              return p
                                            }, this)
                       };

so that it perfectly returns a reference to the array it's called upon.

like image 89
Redu Avatar answered Oct 18 '22 16:10

Redu