Faced an interesting (for me) example:

archive(): void { var oldTodos = this.todos; console.log(this.todos); console.log(oldTodos); this.todos = []; console.log(oldTodos); console.log(this.todos); oldTodos.forEach((todo: Todo) => { if (!todo.done) this.todos.push(todo); }); } 

The array has a reference type, right? And, like, this.todos = []; It should just rub the array and all links will now have an empty array, but this is not the case and it does not behave like a reference type. What is the matter and where am I mistaken? All code: http://plnkr.co/edit/x0aeMXEwYo67pAWYXzfA?p=preview

    1 answer 1

    Did not quite understand the question:

    1. there was a link to the array: this.todos

    2. save this link to the var oldTodos = this.todos;
      now there are two links to one array: this.todos and oldTodos

    3. assigned this.todos link to the new array this.todos = [];
      now this.todos refers to [] , and oldTodos continues to reference the old array

    4. We run through the old array and copy the links to its elements into a new one.

    The array here behaves quite like a reference type.

    Perhaps if the filter method were used it would be clearer.

     archive(): void { this.todos = this.todos.filter((todo: Todo)=> !todo.done); }