1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Classes Explained: Private Fields, Static Members and Extends

JavaScript classes give you a clean way to bundle data and behaviour. Learn constructors, methods, #private fields, getters, static members, extends and super, plus the errors you will hit, with output from tested Node.js code.

9 min read
JavaScript classes explained: private fields, static members and extends

Key takeaways

  • JavaScript classes are cleaner syntax over prototypes. typeof a class is still "function".
  • Fields that start with # are truly private. Code outside the class cannot read them, and naming one there is a syntax error.
  • static members belong to the class itself, and extends plus super() handle inheritance.
  • Classes must be called with new, are not hoisted for use, and methods lose this when passed around unless you bind them or use arrow fields.

Before 2015, building objects in JavaScript meant constructor functions and editing prototype by hand. It worked, but it was easy to get wrong and hard to read. JavaScript classes fixed the readability, and later additions such as private fields and static blocks made them a real tool for organising code.

In this guide we build one small banking example step by step, then cover inheritance, how classes relate to prototypes, and the mistakes that cause bugs. We ran every snippet with Node.js 24.22.1 as an ES module, so strict mode was on.

What is a class in JavaScript?

A class is a blueprint for objects. It describes the data each object holds and the methods that work on that data. You create objects, called instances, with new. Classes are a good fit when you will create many objects with the same shape and behaviour, such as users, orders, page objects in a test suite or UI components.

If you are new to the language, our JavaScript tutorial for beginners covers objects and functions first.

A first class: fields, constructor and methods

class Account {
  #balance = 0;
  static count = 0;

  constructor(owner, opening = 0) {
    this.owner = owner;
    this.#balance = opening;
    Account.count++;
  }

  deposit(amount) {
    if (amount <= 0) throw new RangeError("amount must be positive");
    this.#balance += amount;
    return this;
  }

  get balance() { return this.#balance; }

  static compare(a, b) { return a.#balance - b.#balance; }

  toString() { return `${this.owner}: ${this.#balance}`; }
}

const a = new Account("Asha", 100).deposit(50);
console.log(String(a));   // Asha: 150

The parts:

  • Field declarations such as #balance = 0 set up each instance before the constructor body runs.
  • The constructor runs once per new call and receives the arguments.
  • Methods such as deposit() live on the prototype and are shared by every instance. Returning this lets you chain calls.
  • Getters such as balance look like properties to callers.

Private fields with #

A field whose name starts with # is private to the class body. It is not a naming convention like the old underscore prefix. The engine enforces it:

console.log(a.balance, a["#balance"], Object.keys(a));
// 150 undefined [ 'owner' ]

The getter returns 150. The bracket lookup finds nothing, because "#balance" as a string is just an ordinary missing property. Object.keys() lists only owner. And if code outside the class writes #balance directly, the file does not even load. Node stopped our script before running it:

SyntaxError: Private field '#balance' must be declared in an enclosing class

Notice that the static method compare(a, b) can read a.#balance of another instance. Privacy is per class, not per object, so any code inside the class body can see the private fields of any instance of that class. You can also write private methods, such as #validate(), the same way.

Getters and setters

A getter computes a value on read, and a setter runs on write. Our class has a getter but no setter, so balance is read-only:

try { a.balance = 5 } catch (e) { console.log(e.name + ": " + e.message) }
// TypeError: Cannot set property balance of [object Object] which has only a getter

That error appears because class bodies and modules run in strict mode. In old sloppy-mode scripts, the assignment would fail silently, which is much harder to debug. Use a setter when you want to validate input on assignment, for example set email(v) { if (!v.includes("@")) throw ...; this.#email = v; }.

Static members

static puts a property or method on the class itself rather than on instances. In our example, Account.count tracks how many accounts were created, and Account.compare works as a sort comparator:

const s = new Savings("Ravi", 1000, 0.05).addInterest();
console.log(Account.count);                                  // 2
console.log([s, a].sort(Account.compare).map(x => x.owner)); // [ 'Asha', 'Ravi' ]

Static members suit factory methods such as User.fromJSON(), shared constants, and helpers that work across instances. You cannot call a static method on an instance, so a.compare is undefined. For more on comparators, see our JavaScript sort guide.

Inheritance with extends and super

class Savings extends Account {
  constructor(owner, opening, rate) {
    super(owner, opening);   // must run before using this
    this.rate = rate;
  }
  addInterest() { return this.deposit(this.balance * this.rate); }
  toString() { return `${super.toString()} (savings ${this.rate * 100}%)`; }
}

console.log(String(s));
// Ravi: 1050 (savings 5%)

Three rules to remember:

  1. A subclass constructor must call super() before it touches this. Otherwise you get a ReferenceError.
  2. super.method() calls the parent version, which is how toString() above extends rather than replaces the parent output.
  3. The subclass cannot read the parent’s #balance directly. It goes through the public balance getter and deposit(), which keeps the parent in control of its own data.

Count went to 2 because the Savings constructor called the parent constructor through super(). Keep inheritance shallow. One level, as here, is easy to follow. Deep chains get fragile, and composition, meaning an object that holds other objects, is often simpler.

Classes are still prototypes

console.log(s instanceof Account, Object.getPrototypeOf(Savings) === Account, typeof Account);
// true true function
console.log(Object.getOwnPropertyNames(Account.prototype));
// [ 'constructor', 'deposit', 'balance', 'toString' ]

A class is a special function, and its methods sit on Account.prototype, exactly as with the old pattern. Static compare is missing from that list because it lives on Account itself. Knowing this explains a lot of behaviour, including why methods are shared and how instanceof works.

The lost this problem

Methods do not remember their object. If you pull a method out and call it alone, this is undefined:

class Btn {
  label = "OK";
  handle() { return this?.label }
  arrow = () => this.label
}
const b = new Btn();
const { handle, arrow } = b;
console.log(handle(), arrow());
// undefined OK

This bites when you pass a method as a callback, for example to addEventListener or setTimeout. Two fixes: write the method as an arrow function field, as arrow above, which captures this per instance, or bind it with this.handle = this.handle.bind(this) in the constructor. Our guide to the this keyword explains the rules in depth.

Errors you will see

Code Error from our run Cause
Account("x") TypeError: Class constructor Account cannot be invoked without ‘new’ Forgot new
new Hoisted() before the class line ReferenceError: Cannot access ‘Hoisted’ before initialization Classes are not usable before their declaration
a.deposit(-1) RangeError: amount must be positive Our own validation
a.balance = 5 TypeError: … which has only a getter No setter defined

When should you use classes?

Use a class when many objects share behaviour and state, when you want real privacy with # fields, or when a framework expects one, such as page objects in Playwright test suites. Our Page Object Model guide shows that pattern. Prefer plain objects and functions for simple data, one-off helpers and code where a closure is enough. Our closures guide shows how closures also give you private state.

Best practices

  • Use # fields for internal state instead of underscore names.
  • Validate in the constructor and setters so an object can never be in a bad state.
  • Keep classes small and focused on one job.
  • Prefer composition over deep inheritance chains.
  • Use arrow function fields for methods that will be passed as callbacks.
  • In TypeScript, the same syntax works, with extra checks. See our TypeScript tutorial.

Static initialization blocks

When a static property needs more than a one-line value, use a static { } block. It runs once, when the class is defined:

class Config {
  static defaults;
  static {
    Config.defaults = Object.freeze({ retries: 3, timeout: 5000 });
    console.log("static block ran");
  }
}
console.log(Config.defaults, Object.isFrozen(Config.defaults));
// static block ran
// { retries: 3, timeout: 5000 } true

Static blocks can also read private static fields, which makes them handy for setting up lookup tables or validating configuration before any instance exists.

Final thoughts

JavaScript classes give structure without hiding how the language works underneath. Declare fields at the top, make internal state private with #, expose it through getters and methods, use static for class-level helpers, and inherit with extends and super() only when it truly fits. Remember that a class is still a function with a prototype, and most of the surprising behaviour will make sense.

FAQ

Are JavaScript classes just syntactic sugar?

Mostly. They are built on prototypes and typeof a class is function. But they add real features such as private fields, strict mode by default and a required new keyword.

How do I make a private property in a JavaScript class?

Start the field name with a hash, as in #balance. Only code inside the class body can read or write it, and the engine enforces this.

What does super do in JavaScript?

In a subclass constructor, super calls the parent constructor and must run before you use this. In methods, super.method calls the parent version of that method.

What is a static method in a JavaScript class?

A static method belongs to the class itself, not to instances. You call it as ClassName.method, which suits factories and helpers.

Are JavaScript classes hoisted?

The declaration is hoisted but not initialized, so using a class before its line throws a ReferenceError. Always declare classes before you use them.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Software Development

Python Datetime: Format, Parse and Time Zones

Python datetime explained with tested code: strftime, strptime, timedelta, ISO 8601, zoneinfo time zones, timestamps and the DST and naive…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →