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.

Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Software Development

Python Map and Filter: Examples vs List Comprehensions

Python map and filter explained with tested examples: lazy map objects, multiple iterables, filter(None), chaining, and a timed comparison with…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
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 →
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 →
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 →
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 →
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 →
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 →
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 →