1

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

1 Answer 1

1

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.

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

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.