Why doesn't concat update this array?

I’m pushing new values into this array after concatenating it. But when I console: log it, the new values aren’t reflected. Apparently it doesn’t re-check to see the values of the array before logging it?

let drugs = [ 'Pills', 'Powder', 'Smoke' ];
let all = [];
all = all.concat(drugs);
drugs.push('alcohol', 'caffeine');
console.log(all);

‘alcohol’ and ‘caffeine’ aren’t logged. Apparently concat only combines what is present at the time it’s run?

When in doubt, check the documentation!

Concat makes a brand new array that is not connected to the original array.

1 Like
let drugs = [ 'Pills', 'Powder', 'Smoke' ];
let all = [];
all = all.concat(drugs);
all.push('alcohol', 'caffeine');
console.log(all);

Try this

1 Like

@JeremyLT Thanks. I see concat doesn’t change the original array but drugs.push('alcohol', 'caffeine'); does, no?
So I guess all does not “update”?..

1 Like

What did you expect? You are console.logging all after pushing elements to drugs not all. You concatenated all and drugs and then pushed elements to drugs later.

2 Likes

Exactly. all is a copy of the array, and after you create the copy it doesn’t know about changes to drugs.

1 Like

Elements of the original arrays are copied into the new array as follows:

Object references (and not the actual object): concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments that are also arrays.

Data types such as strings, numbers and booleans (not String, Number, and Boolean objects): concat copies the values of strings and numbers into the new array.

let drugs = [ 'Pills', 'Powder', 'Smoke', ['test'] ];
let all = [];
all = all.concat(drugs);
console.log(all); // [ 'Pills', 'Powder', 'Smoke', [ 'test' ] ]

drugs[3][0] = 'something new'
console.log(all); // [ 'Pills', 'Powder', 'Smoke', [ 'something new' ] ]
1 Like