30 min·intermediate

Lesson 8

Prototypes & private state

Build a practical mental model for prototypes & private state and use it in working JavaScript.

By the end, you will be able to…

  • Explain prototypes & private state in your own words
  • Use prototypes & private state in a small program
  • Recognize and debug a common failure mode

Build the mental model

Every object has an internal prototype it delegates missing lookups to, forming a chain that ends at Object.prototype, then null. Private class fields (#count) are a modern way to hide state that the prototype chain will never expose to outside code.

your object
prototype
Object.prototype
null
The prototype chain

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: 1 2

Why this matters

Understanding the prototype chain explains where array/object built-in methods (like .map or .hasOwnProperty) actually come from, and private fields prevent accidental external mutation of internal state.

Real-world example

Every library's internal counters, caches, or connection state use private fields exactly like this to prevent consumers from reaching in and corrupting them.

Common mistakes

  • Trying to access a #privateField from outside the class and being surprised by the SyntaxError
  • Assuming every object property is 'own' when many are inherited via the prototype chain
  • Manually reassigning an object's prototype in hot code paths, which is slow and rarely necessary

Try it yourself

Challenge

Add a #balance private field to BankAccount with a public getBalance() method.

Practice

Knowledge check

What happens if you try to access a class's #privateField from outside the class body?

Summary

Objects delegate missing properties up a prototype chain; private class fields (#field) hide implementation state completely.