Ben Ben - 1 month ago 8
TypeScript Question

Typescript array push, strange behaviour with console.log

When I try to log an array before and after a array push, the output is the same for both:

class MyClass {
order: number;
}

let list: MyClass[] = [];

for (let i = 0; i < 5; i++){
list.push({ order: i });
}
console.log('before push', list);
list.push({ order: 999 });
console.log('after push', list);


The 'before push' contains MyClass with order 999. Why?
You can try yourself here:
Playground

Answer

The reason is that you log the same array instance, and the console saves a reference to that instance.
So in both prints it print the same instance, and when you change the instance after the first print, the instance in the console changes as well.

The console shows something like this:

before push [Object, Object, Object, Object, Object]
after push [Object, Object, Object, Object, Object, Object]

So it looks like at first there are 5 items and then 6, but when you open the array in the console it shows 6 items in both cases, because it's the same instance.

If you want the first print to stay with the data before the push then do this:

console.log('before push', list.slice(0));
list.push({ order: 999 });
console.log('after push', list);

The slice method creates a new array from the passed index on, so it basically clones the array.

Comments