Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use `concat` instead of `push` in this instance?

I was browsing the answers to this question: Can I dispatch an action in reducer? and in this answer, I see the following:

actionQueue = actionQueue.concat([asyncAction]);

which is essentially the same as:

actionQueue.push(asyncAction);

(ignoring that the concat call is creating a new array and re-assigning it to actionQueue, the result is the same -- an array with asyncAction appended to it).

Initially, I thought that it (perhaps) performed better (somehow), and someone else was apparently wondering the same as they beat me to it in jsperf: Array .concat() vs. .push().

As the results of the jsperf testing show, the concat method is significantly slower than push (at least as far as Chrome is concerned).

Is there something I'm missing?
Is there a reason concat would be preferred in this use case?

like image 746
pete Avatar asked Jan 24 '18 17:01

pete


People also ask

What is the difference between concat and push?

concat returns a new array while push returns the length of updated array. Because concat creates a new array to hold the result of merged arrays, it's slower than push . For small arrays, both methods do not produce a significant difference in term of performance.

What is the difference between Myarray push element and Myarray concat element )?

The push() adds elements to the end of an array and returns the new length of the array. Thus your return here is invalid. The concat() method is used to merge arrays. Concat does not change the existing arrays, but instead returns a new array.

Can push () be used on string?

The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

What is the use of concat apply ()?

It's a property from concat() that does the heavy lifting, “apply” just executes the method. So what you're saying is that the concat function on arrays (i.e. Array. protype. concat ([x]) will always reduce [x] by 1 array level i.e. if arr = [1,2] it will become 1,2 and if arr = [[1,2]] it will become [1,2]).


2 Answers

If some other code has a reference to the existing array in actionQueue, using concat will not affect that.

var a1 = [1];
var b1 = a1
a1 = a1.concat([2])

var a2 = [1];
var b2 = a2
a2.push(2)

console.log('b1', b1)
console.log('b2', b2)
like image 58
SLaks Avatar answered Sep 21 '22 08:09

SLaks


Push()

The push() method is a generic method similar to call() or apply(). It will mutate your array (or object), pushing a new value into it.

Push: MDN

Concat()

The concat() method returns a new array, with the values merged. This also avoids mutation side effects.

Concat: MDN

like image 21
Rex Avatar answered Sep 22 '22 08:09

Rex