14

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?

1
  • 1
    I believe it's all to do with immutability Commented Jan 24, 2018 at 17:14

3 Answers 3

14

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)

Sign up to request clarification or add additional context in comments.

3 Comments

even though the new array created by concat is being reassigned to the same variable?
@pete: That's only one variable. It doesn't affect other references to the array.
I added a code sample to the answer to help make it clearer. Hopefully @SLaks does not mind me doing it :)
12

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

Comments

5

In simple push append the array in the same reference, while concat doestn't effect the orignal array. Check out following snippet

let x = [1,2,3,4];
let y = x.concat(5);
// At this step y hold [1,2,3,4,5] and x remain unchanged to [1,2,3,4]
document.write('x=>'+x);
document.write('y=>'+y);

let z = x.push(5);
// At this step z hold 5 and x is now changed to [1,2,3,4,5]
document.write('x=>'+x);
document.write('z=>'+z);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.