Different results with concat()

Hi there, I’ve come across some very odd behaviour when using concat within a function. The easiest way for me to explain is with some code:

function matchStuff(objArr, stuff) {
  var arr = [];
  // What's going on here?

  // outputs a populated array
  //[ { first: 'Romeo', last: 'Montague' } ]

  // outputs [] (an empty array)
  // **********************
  return arr;

matchStuff([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

This seems completely nuts to me! Could someone please shed light on this because I quite often test stuff by putting it in a console.log() statement first to make sure it does what I expect. I got tripped up a bit here though! Do I need to change this way of testing stuff?

Thanks in advance for any help on this.


That’s because here console.log(arr.concat(objArr[0])); you are logging the return value of the .concat() method.

And here console.log(arr); you are logging the empty array arr.

.concat() returns a new array. It does not modify the array. If you want to modify an array, you probably want .push() or .shift().

OMG! That really put my head into meltdown :confounded:

you are logging the return value of the .concat() method.

This is a really important subtle nuance that just passed me by.

I’ve just been trawling through my notes trying to make sense of what you said and I think I know where my misunderstanding stemed from. My notes from the curriculum for example:

> Add Elements to the End of an Array Using concat Instead of push

Concat offers a way to add new items to the end of an array without any mutating side effects.

function nonMutatingPush(original, newItem) {
  return original.concat(newItem); // [ 1, 2, 3, 4, 5 ]
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);

Would I be correct in saying the following

return original.concat(newItem); // [ 1, 2, 3, 4, 5 ]

yeilds the same result as
console.log(original.concat(newItem)); // [ 1, 2, 3, 4, 5 ]
with the latter outputting to the console of course?

And the misunderstanding I had was in assuming that original was altered, whereinfact it was not?.

In my original function, I simply needed to write:

arr = arr.concat(objArr[0]);

in order to get the same result as I saw when using console.log(). This seems to work, or am I missing something else here?

You’ve got it. Congratulations!

Thank you for clearing this up for me. Its a great help, I really had no idea that console.log() was doing that. I will be more careful in the future!


I’m glad I could help. Happy coding!