MediumPrototypes & Inheritance🐛 Debug Challenge

Shared array on prototype mutates all instances

Buggy Code — Can you spot the issue?

function TodoList() {}
TodoList.prototype.items = [];

const list1 = new TodoList();
const list2 = new TodoList();

list1.items.push('Buy milk');
console.log(list1.items.length);
console.log(list2.items.length);

Fixed Code

function TodoList() {
  this.items = [];
}

const list1 = new TodoList();
const list2 = new TodoList();

list1.items.push('Buy milk');
console.log(list1.items.length);
console.log(list2.items.length);

Bug Explained

Bug: Arrays on the prototype are shared by all instances. list1.items.push() mutates the single shared array, so list2 sees it too.

Explanation: Initializing items in the constructor creates a fresh independent array per instance.

Key Insight: Never put mutable state on a prototype. Always initialize arrays and objects in the constructor.

More Prototypes & Inheritance Debug Challenges

MediumhasOwnProperty vs in — different results for prototype method

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab