CodePark/ questions / Prototypes & classes
START PRACTICINGPRACTICE
Frontend question · JavaScript › Prototypes & classes

What does this log?

function Team() {}
Team.prototype.members = [];

const a = new Team();
const b = new Team();
a.members.push("Ann");
a.tags = ["x"];
console.log(b.members.length, b.tags);
1 undefined

The answer is 1 undefined. a.members.push reads members through the prototype chain. It changes the single array stored on the prototype, so b sees Ann too. Assigning a.tags creates an own property on a only, so b.tags is undefined.

The tempting option "0 undefined" is wrong because
push does not create a new array on a. It changes the shared one. This is why changeable state belongs in the constructor, not on the prototype.