JavaScript Classes: class Syntax, Constructors, Methods, Fields, Static Members and Private #fields
Everything in a modern JavaScript class: constructors, methods, getters and setters, public fields, static methods, fields and blocks, private #fields and #methods, #x in obj checks, arrow-function fields for callbacks, class expressions, strict mode, hoisting, and how it all maps onto prototypes.
kvi5hnuCode Sprout team member7 min readOn this page
ES2015 introduced the class keyword, and ES2022 completed it with fields, private members and static blocks. Underneath, a class is still a constructor function plus a prototype (article 70), but the syntax is clearer, safer, and adds real privacy. This article covers every kind of class member.
A first class
class Account {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
return this;
}
toString() {
return `${this.owner}: $${this.balance}`;
}
}
const acct = new Account("Ana");
acct.deposit(50).deposit(25);
console.log(String(acct), acct instanceof Account);
console.log(typeof Account, Object.getOwnPropertyNames(Account.prototype));
Ana: $75 true
function [ 'constructor', 'deposit', 'toString' ]
constructorinitializes each new instance. If you leave it out, an empty one is created for you.- Methods use shorthand syntax with no commas between them; they're stored on
Account.prototypeand shared by all instances, exactly like article 70's prototype methods. typeof Accountis"function": a class is a constructor function.
What class adds over constructor functions
class Account {}
try {
Account(); // calling without new
} catch (err) {
console.log(err.name);
}
try {
new Later(); // using a class before its declaration
} catch (err) {
console.log(err.name);
}
class Later {}
TypeError
ReferenceError
- A class can't be called without
new. - Class declarations aren't hoisted like function declarations: like
let, they're in the temporal dead zone until the declaration runs. - The whole class body is strict mode automatically, so a detached method gets
this === undefinedrather than the global object. - Methods are non-enumerable (they don't show up in
for...inover instances) and can't be used withnew.
Class expressions
Like functions, classes can be expressions, optionally named (the name is visible only inside the class):
const Square = class {
constructor(side) { this.area = side * side; }
};
console.log(new Square(3).area, Square.name);
9 Square
Class expressions are mostly used when a function creates and returns a class, as in mixins (article 74).
Getters and setters
Accessor properties (article 53) work in classes the same way, and they live on the prototype:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(f) {
this.celsius = (f - 32) * 5 / 9;
}
}
const t = new Temperature(100);
console.log(t.fahrenheit);
t.fahrenheit = 32;
console.log(t.celsius);
212
0
Generator methods (*[Symbol.iterator]() {...}, part 12), async methods and computed method names ([name]() {...}) are also allowed.
Public fields
Fields (ES2022) declare instance properties directly in the class body, with an optional initializer:
class Order {
items = []; // a new array for EVERY instance
status = "open";
createdBy; // undefined until assigned
itemCount = this.items.length; // initializers can use this and earlier fields
constructor(user) {
this.createdBy = user;
}
}
const first = new Order("ana");
const second = new Order("bo");
first.items.push("pen");
console.log(first.items, first.status, first.createdBy, first.itemCount);
console.log(second.items, Object.keys(second));
[ 'pen' ] open ana 0
[] [ 'items', 'status', 'createdBy', 'itemCount' ]
Field initializers run for each instance when it's created (right after super() in subclasses, or at the start of the constructor otherwise), so items = [] gives each order its own array. Fields are own properties of the instance, not prototype properties. Declaring them at the top documents the shape of every instance at a glance, which editors and TypeScript also use.
Arrow-function fields for callbacks
A field initialized with an arrow function creates a per-instance function whose this is permanently the instance, which fixes the "lost this" problem for callbacks (article 64):
class Counter {
count = 0;
increment = () => {
this.count++;
return this.count;
};
}
const counter = new Counter();
const detached = counter.increment; // e.g. passed to an event listener
detached();
console.log(detached(), Object.keys(counter));
2 [ 'count', 'increment' ]
The trade-off: each instance gets its own copy of the function (not shared via the prototype), and subclasses can't call it with super.increment(). It's a good choice for event handlers in UI components; use normal methods otherwise.
Static members
Static methods and fields belong to the class itself (the constructor function), not to instances. Use them for factory methods, utilities and constants related to the class:
class Temperature {
static FREEZING_C = 0;
static fromFahrenheit(f) { // an alternative constructor
return new Temperature((f - 32) * 5 / 9);
}
constructor(celsius) {
this.celsius = celsius;
}
}
const boiling = Temperature.fromFahrenheit(212);
console.log(boiling.celsius, Temperature.FREEZING_C, boiling.FREEZING_C);
try {
boiling.fromFahrenheit(32);
} catch (err) {
console.log(err.name); // not available on instances
}
100 0 undefined
TypeError
Built-ins are full of static methods: Array.from, Object.keys, Number.isInteger, Promise.all. Inside a static method, this is the class (when called as Temperature.method()), which also makes static methods work correctly for subclasses.
Static initialization blocks
A static { ... } block (ES2022) runs once when the class is defined, for setup that needs more than one expression:
class Config {
static defaults;
static {
const env = { mode: "dev" }; // imagine reading real settings here
Config.defaults = Object.freeze({ debug: env.mode === "dev", retries: 3 });
}
}
console.log(Config.defaults);
{ debug: true, retries: 3 }
Private members: #fields and #methods
Names starting with # are private (ES2022): they can only be used inside the class body. Unlike the old convention of an underscore prefix (_balance), this is enforced by the language:
class Wallet {
#balance = 0; // must be declared in the class body
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
this.#validate(amount);
this.#balance += amount;
return this.#balance;
}
get balance() { // read-only public access
return this.#balance;
}
#validate(amount) { // private method
if (!(amount > 0)) throw new RangeError("Amount must be positive");
}
}
const w = new Wallet("Bo");
w.deposit(40);
console.log(w.balance, w["#balance"], Object.keys(w), JSON.stringify(w));
try {
w.deposit(-5);
} catch (err) {
console.log(err.name, err.message);
}
40 undefined [ 'owner' ] {"owner":"Bo"}
RangeError Amount must be positive

Key facts about private members:
- Truly hidden: they aren't properties at all.
Object.keys,JSON.stringify,for...in, spread and even proxies can't see them. Writingobj.#balanceoutside the class is a SyntaxError (it's caught before the code runs). - They must be declared in the class body; you can't create new ones dynamically.
- They're per class, not per object: code in
Walletcan read#balanceof anotherWalletinstance, which is handy forequalsormergemethods. - Private methods, getters, static members (
static #count) all work the same way. #field in objchecks whether an object has that private field, a reliable "is this really one of mine?" test:
class Token {
#secret = "s3";
static isToken(value) {
return #secret in value;
}
}
console.log(Token.isToken(new Token()), Token.isToken({ secret: "s3" }));
true false
Accessing a private field on an object that doesn't have it throws a TypeError, so #x in obj is the safe way to check first.
One limitation: structuredClone and other copying tools can't copy private fields, and the copy loses the class (it becomes a plain object), so classes with private state need their own clone() method.
Private vs underscore vs closure privacy
| Approach | Truly private? | Notes |
|---|---|---|
this._balance (convention) | no | Anyone can read and write it; a signal to other developers only |
| Closure variables (article 67) | yes | New function copies per instance; no class syntax |
#balance | yes | Enforced by the language; works with prototype methods |
TypeScript private balance | compile-time only | Erased in the JavaScript output; still accessible at runtime |
A complete example
class Fraction {
#num;
#den;
static ZERO = new Fraction(0, 1);
constructor(numerator, denominator = 1) {
if (denominator === 0) throw new RangeError("Denominator can't be zero");
const sign = Math.sign(denominator);
const g = Fraction.#gcd(Math.abs(numerator), Math.abs(denominator)) || 1;
this.#num = (sign * numerator) / g;
this.#den = Math.abs(denominator) / g;
}
static #gcd(a, b) {
return b === 0 ? a : Fraction.#gcd(b, a % b);
}
static parse(text) {
const [n, d = "1"] = text.split("/");
return new Fraction(Number(n), Number(d));
}
plus(other) {
return new Fraction(this.#num * other.#den + other.#num * this.#den, this.#den * other.#den);
}
equals(other) {
return #num in other && this.#num === other.#num && this.#den === other.#den;
}
get value() {
return this.#num / this.#den;
}
toString() {
return this.#den === 1 ? `${this.#num}` : `${this.#num}/${this.#den}`;
}
}
const half = Fraction.parse("2/4");
const third = new Fraction(1, 3);
console.log(`${half} + ${third} = ${half.plus(third)}`);
console.log(half.equals(new Fraction(1, 2)), half.value, String(Fraction.ZERO));
1/2 + 1/3 = 5/6
true 0.5 0
This uses a private field per instance, a private static helper, a static factory and constant, an accessor, and access to another instance's private fields in plus and equals.
Common questions
Are JavaScript classes "real" classes?
They're real in the sense that matters: they define types with constructors, methods, inheritance and private state. Underneath they use prototypes, so they behave differently from Java or C# classes in some respects: methods can be added at runtime, this depends on how a method is called, and there are no interfaces or method overloading.
Should methods be arrow-function fields or normal methods?
Normal methods by default: they're shared on the prototype, support super, and appear in the class's API. Use arrow fields only for functions that are passed around as callbacks and need a fixed this.
Why does this.#x = 1 in the constructor throw a SyntaxError?
Private fields must be declared in the class body (#x; or #x = 1;) before any method can use them. Without the declaration, #x is an unknown private name.
Can I have private fields in object literals?
No. # names only exist in class bodies. For private state in plain objects, use closures.
Summary
- A class is a constructor function with methods on its prototype; it can't be called without
new, isn't hoisted, and its body is strict. - Methods, getters, setters, generators and computed names work as in object literals, but without commas.
- Public fields (
items = []) become own properties of each instance, initialized per instance; arrow-function fields give callbacks a fixedthis. staticmethods, fields and blocks belong to the class itself: use them for factories, constants and utilities.#privatefields and methods are enforced by the language, invisible outside the class body, accessible across instances of the same class, and testable with#x in obj.
Practice Questions
What does this print?
class A {
static n = 1;
m = 2;
}
const a = new A();
console.log(A.n, a.n, A.m, a.m);
Answer
1 undefined undefined 2. Static fields live on the class, instance fields on each instance.
What's wrong with this class (snippet A) when used as in snippet B, and what happens?
class Cart {
items = [];
add = (x) => this.items.push(x);
total() {
return this.items.length;
}
}
const add = new Cart().add;
add(1);
Answer
Nothing is wrong: add is an arrow-function field, so its this is permanently the instance, and the detached call works. If add had been a normal method, the detached call would throw a TypeError because this would be undefined.
Write a class Stack with a private array, push, pop, and a read-only size getter.
Answer
class Stack {
#items = [];
push(x) {
this.#items.push(x);
return this;
}
pop() {
return this.#items.pop();
}
get size() {
return this.#items.length;
}
}
What does this code return?
Object.keys(new (class { #a = 1; b = 2; get c() { return 3; } })())
Answer
[ 'b' ]. The private field isn't a property, and the getter lives on the prototype, so only the public field b is an own enumerable key.
Previous: JavaScript Prototypes and Constructor Functions: How Classes Work Underneath
Next: JavaScript Subclasses: extends, super, Overriding Methods and Extending Built-ins

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.