Lesson 23 of 28

In progress

Course progress

JavaScript

Classes and private fields

Write classes with constructors and methods, extend them with super, and keep internal state private with # fields.

A class is a template for objects that share behaviour. JavaScript’s version is built on prototypes, but the class syntax is easier to read and covers most application code.

What you will learn

  • Define a class with a constructor and methods.
  • Use getters, static members and private fields.
  • Extend a class with extends and super.

A class in practice

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

#count is a private field: it is inaccessible outside the class, and clicks.count is simply undefined. That is real privacy, not a naming convention, and it makes the public surface of the class obvious.

Methods live on the prototype, so every instance shares them. Fields declared with = run per instance, before the constructor body.

Getters and setters

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

A getter computes a value on read; a setter validates on write. Validation in a setter is the class’s main advantage over a plain object: no caller can put it into an invalid state without an error.

Throwing from a setter is appropriate for programmer errors. For user input, validate before assigning and show a message instead.

Static members

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

Static members belong to the class, not an instance. They are right for helpers that do not depend on a particular object, such as a conversion table or a factory. A static method that only formats a value could be a plain function; use classes when the grouping earns its keep.

Inheritance

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

super(...) runs the parent constructor and must be called before using this in the subclass constructor. super.method() calls the parent implementation, which is how you extend rather than replace behaviour.

Two levels are usually enough. When a hierarchy grows, composition — an object holding another object — is easier to change and test.

Changing state safely

A class is a good place to keep invariants, the rules that must always hold. If every method goes through the same validation, no caller can leave the object in an impossible state.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The array is private, so the only way to add an item is through add, which checks it. total is computed from the same data, so it cannot drift out of sync the way a stored total can.

Printing and serialising

toString() controls how an instance becomes text, and toJSON() controls what JSON.stringify stores. Both are worth defining when an object is logged or saved.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

Without toJSON, stringify would include every enumerable field, including ones you consider internal. With it, the stored shape is explicit and can differ from the in-memory shape.

Classes or factories?

A class suits state with behaviour and validation, especially when several instances exist. A closure-based factory suits a single object with private state and no inheritance.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

Private fields are also skipped by Object.keys, JSON.stringify and spread, which keeps internal state out of logs and out of accidental copies. Expose what callers need through getters rather than reaching for the field itself.

Both are valid. Choose the one that reads better at the call site, and do not mix styles within one feature.

Using an arrow function for a class method does not create a prototype method; it creates a per-instance field. That costs memory per object and breaks super calls. Use the method shorthand methodName() {} in classes, and arrows only for callbacks passed to other functions.

Write a Playlist class with a private #songs array, an add(song) method, a length getter and a toString() method. Then create two playlists and show that their contents are independent.

Show solution
JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The private array is created per instance, so the two playlists cannot share it. Returning this from add allows chaining without exposing the array.

Recap

  • #fields are genuinely private; getters and setters control access.
  • Static members belong to the class; super extends a parent constructor or method.
  • Prefer shallow inheritance or composition, and use method shorthand rather than arrow fields.

Next, you will look at the tooling around real projects: npm, debugging and tests.

Do classes change how this works?
They make it more predictable: a normal method gets the instance as `this`, while an arrow field captures the surrounding `this`.
Can I add a method to a class later?
You can add to the prototype, but it is hard to discover and breaks with private fields. Edit the class instead.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.