🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Class Fields

A class field is a value declared inside a class body. The field belongs to each instance made from the class.

Declare fields in the class body

This class declares two fields and no constructor. The fields still exist on every instance.

class Player {
  name = "Unnamed";
  score = 0;
}

Read a field from an instance

new builds an instance with the field values. The code reads both fields through the instance.

class Player {
  name = "Ada";
  score = 0;
}

const player = new Player();
console.log(player.name);
console.log(player.score);

Each instance keeps its own fields

Changing a field on one instance leaves the other instance alone. Each instance holds its own copy.

class Player {
  name = "Ada";
  score = 0;
}

const first = new Player();
const second = new Player();
first.score = 10;
console.log(first.score);
console.log(second.score);

Fields work with methods

A method reads and changes a field through this. Two calls raise the count to 2.

class Counter {
  count = 0;

  add() {
    this.count = this.count + 1;
  }
}

const counter = new Counter();
counter.add();
counter.add();
console.log(counter.count);

Example

class Book {
  title = "Unknown title";
  pages = 0;

  describe() {
    return this.title + " has " + this.pages + " pages.";
  }
}

const book = new Book();
book.title = "Dune";
book.pages = 896;
console.log(book.describe());

Key points

  • Field: a value declared inside the class body, outside any method
  • A field needs no assignment inside the constructor.
  • Each instance gets its own copy of every field.
  • A field can hold a starting value, such as 0 for a count.
  • A method reads a field through this, the same as a constructor value.
  • Fields are set before the constructor body runs, so the constructor can read them.

In this example, the Book class declares two fields with starting values. The code changes both fields on one instance. The describe method reads the fields and returns one sentence.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Where is a class field declared?