Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

class — classes, constructors, and fields

The class keyword defines a class built on JavaScript prototypes. Learn the role of constructor, the distinction between instance fields and methods, and the rules for creating objects with new.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

class Name { field = initialValue; constructor(value) { this.field = value; } method() { return this.field; } }

class is a reserved keyword defining a class through a declaration, class Counter {}, or an expression, const Counter = class {};. Classes use prototypes, and code inside their bodies runs in strict mode. A class declaration's binding is block-scoped; reading it before the declaration executes causes a ReferenceError.

The class constructor is the special constructor method that initializes an instance during new Counter(2). Only one is permitted; if omitted, the language supplies a default constructor. Calling Counter(2) without new causes a TypeError. Ordinary methods such as increment reside on Counter.prototype and are shared by instances.

class fields, such as value = 0;, create each instance's own state. In a base class they initialize before the constructor body; in a derived class they initialize after the superclass constructor returns, but before the super() call expression finishes evaluating. A field without an initializer receives undefined. Fields marked static belong to the class, while #name fields are private. extends specifies inheritance; a derived constructor must call super() before using this.

In the example, the constructor overwrites the initial value, and the method changes only the selected instance. The example requires class-field support, standardized in ECMAScript 2022. Having Node 24 in a repository does not establish browser support; check the target environment separately.

Examples

class Counter {
  value = 0;

  constructor(start) {
    this.value = start;
  }

  increment() {
    this.value += 1;
    return this.value;
  }
}

const first = new Counter(2);
const second = new Counter(10);
console.log(first.increment());
console.log(second.value);
console.log(first.increment === second.increment);

Result

3
10
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources