When I first saw that there was a concat
method in JavaScript, I asked how is that any different than push
? After all pushing values onto an array sounded an awful like concatenating to me. Turns out they are quite similar, but they do things differently and can help in different situations.
Push
The method that I was most familiar with was push
, as that's one of the first ways of manipulating an array that I learned. push
is exceptionally useful as it lets you add one or more elements, that were input arguments, to the array that invoked the method. e.g.
var testArray = [1, 2, 3]; // [1, 2, 3]
var pushResult = testArray.push(4, 5, 6);
console.log(pushResult); // 6
console.log(testArray); // [1, 2, 3, 4, 5, 6]
Wait what is that on the third line? 6? What's the deal with that result? Well the one thing that was not immediately apparent to me when I initially started to use push
a while back, was that it returned the length of the array after adding the new values, not the modified array. This is something that you learn quickly after the first few rounds of unexpected results.
Concat
While push
alters the array that invoked it, concat
returns a new array with the original array joined with the array/s or value/s that were provided as arguments. There are a couple of the things to note about concat
and how it creates the returned array. Both strings and numbers are copied into the array, which means that they if the original value is changed, the value in the new array will be unaffected. This is not true for objects. Instead of copying objects into the new array, the references are copied instead. This means that if the values of objects change in one array, they will also be changed in the other array, as they are references to the objects not unique copies.
var test = [1, 2, 3]; // [1, 2, 3]
var example = [{ test: 'test value'}, 'a', 'b', 4, 5];
var concatExample = test.concat(example); // [1, 2, 3, { test: 'test value'}, 'a', 'b', 4, 5]
example[0].test = 'a changed value';
console.log(concatExample[3].test); // Object { test: "a changed value"}
example[1] = 'dog';
console.log(concatExample[4]); // 'a'
The example is here to illustrate some potential gotchas that might be experienced. The ability to create a new array with the desired values can be very useful in situations, when you don't want to tamper with the input array and you want to do more than just take a copy of the items.
Useful Tools
In the end both of these array methods are extremely useful and will most likely be used with great frequency while programming in JavaScript. Do you have any particular situations where you find yourself using one all the time? Let me know!