Skip to main content

Class Fields Explained – What Is a JavaScript Class Field?

A class field is a property defined directly in a class's body—not inside any of the class's methods.

How to Create Class Fields in JavaScript

You can create a class field by using an equal sign (=)—not a colon (:)—to assign a value to a property.

Here's an example:

// Define a JavaScript class:
class Name {
// Create two class fields:
firstName = "Oluwatobi";
lastName = "Sofela";
}

// Create a new object instance:
const fullName = new Name();

console.log(fullName.firstName + " " + fullName.lastName);

Try Editing It

The Name class in the snippet above has two class fields (firstName and lastName).

Note the following:

  • JavaScript class fields default to undefined if you do not provide any value.
  • Class fields are like the regular object properties whose names you can compute. Let's discuss how.

How to Create Class Fields with Computed Names

You can compute (evaluate) a class field's name by putting an expression in a square bracket like so:

// Initialize a num variable with a number:
let num = 0;

// Assign a string value to an enSuites variable:
const enSuites = "East";

// Define a Room class and compute each of its class fields' names:
class Room {
[enSuites + ++num] = num;
[enSuites + ++num] = num;
[enSuites + ++num] = num;
}

// Create an ensuiteRooms object instance:
const ensuiteRooms = new Room();

// Check the ensuiteRooms's content:
console.log(ensuiteRooms);

// The invocation above will return:
{East1: 1, East2: 2, East3: 3}

Try Editing It

We used the [enSuites + ++num] syntax in the snippet above to compute the class fields' names.

In other words, JavaScript evaluated the enSuites + ++num expression and used the result as each class field's name.

Note: You can also define class fields as regular JavaScript methods. Let's talk more about this now.

How to Create Regular Class Field Methods

You can create a regular class field method by using an equal sign (=) to assign a function to a property.

Here's an example:

// Define a JavaScript class:
class Time {
// Create two regular class field methods:
hourNow = function () {
return new Date().getHours();
};
minutesNow = function () {
return new Date().getMinutes();
};
}

// Create a new object instance:
const currentTime = new Time();

console.log(
`The time is ${currentTime.hourNow()}:${currentTime.minutesNow()}.`
);

Try Editing It

The hourNow and minutesNow methods in the snippet above are class field methods because they are properties containing regular JavaScript functions.

Note: JavaScript allows you to use shorthand syntax to shorten your class's methods. Let's see how.

How to Create Shorthand Class Field Methods

The shorthand class field method is a concise way of defining JavaScript methods in the body of your classes.

Here's an example:

// Define a JavaScript class:
class Time {
// Create two shorthand class field methods:
hourNow() {
return new Date().getHours();
}
minutesNow() {
return new Date().getMinutes();
}
}

// Create a new object instance:

const currentTime = new Time();

console.log(
`The time is ${currentTime.hourNow()}:${currentTime.minutesNow()}.`
);

Try Editing It

Although you can use the regular and shorthand methods interchangeably in your class's body, you should know a significant difference between the two syntaxes. Let's discuss it now.

Regular vs. Shorthand Class Field Methods: What's the Difference?

The main difference between regular and shorthand class field methods is this:

In other words, JavaScript treats regular and shorthand methods differently as follows:

  • Regular method: JavaScript adds the method to the object instance you construct with the new keyword. Therefore, regular methods are own properties of the object instance.
  • Shorthand method: JavaScript adds the method to the class's prototype property. Therefore, shorthand methods are prototypal properties of an object instance.

Here's an example:

// Define a JavaScript class:
class Time {
// Create a regular method:
hourNow = function () {
return new Date().getHours();
};

// Create a shorthand method:
minutesNow() {
return new Date().getMinutes();
}
}

const currentTime = new Time();

// Check currentTime's content:
console.log(currentTime);

// The invocation above will return:
// { hourNow: hourNow() }

Try Editing It

The currentTime object instance contains only the hourNow property because regular methods are instance properties the new keyword assigns to the object it constructs from its constructor class.

On the other hand, shorthand methods are prototypal methods that JavaScript adds to the prototype property of the class you've defined them.

Therefore, you can access the minuteNow method through its class's prototypal inheritance like so:

// Define a JavaScript class:
class Time {
// Create a regular method:
hourNow = function () {
return new Date().getHours();
};

// Create a shorthand method:
minutesNow() {
return new Date().getMinutes();
}
}

// Check Time's prototype content:
console.log(Time.prototype);

// The invocation above will return:
// {...}:
// constructor: class Time {}
// minutesNow: function minutesNow()
// [[Prototype]]: Object {...}

Try Editing It

You can see that Time's prototype property contains the minutesNow method, which all object instances will inherit automatically.

Here's an example:

// Define a JavaScript class:
class Time {
// Create a shorthand method:
minutesNow() {
return new Date().getMinutes();
}
}

// Create an object instance from the Time class:
const currentTime = new Time();

// Check currentTime's content:
console.log(currentTime);

// The invocation above will return an empty object: { }

// Invoke currentTime's minutesNow method:
console.log(currentTime.minutesNow());

Try Editing It

The currentTime.minutesNow() code returned a valid value because currentTime inherited the minuteNow() method from its constructor's prototype property.

Note: A JavaScript class has two types of prototypal methods:

  • User-defined methods
  • Constructor methods

Let's discuss the two types now.

What Is a User-Defined Prototypal Method in JavaScript Classes?

A user-defined prototypal method is the shorthand method you create yourself in the body of your JavaScript class.

Here's an example:

class Name {
firstName(name) {
return name;
}
}

const myName = new Name().firstName("Oluwatobi");

console.log(myName);

Try Editing It

The firstName() method is a user-defined method because we created it ourselves in the body of the Name class.

What Is a Constructor Method in JavaScript Classes?

A constructor() is the default prototypal method that comes built-in with every JavaScript class.

Creating a constructor method is optional. However, if you do not create one, JavaScript will add an empty one automatically.

Here's an example:

class Name {
constructor(name) {
this.name = name;
}
}

const myName = new Name("Oluwatobi");

console.log(myName);

Try Editing It

The Name class above has a constructor method with one instance property in its code block.

JavaScript executes the constructor method before any other user-defined methods. Therefore, it is the best place to define any code you want to run before other methods in the class's body. For instance, consider the code below:

class CarColor {
constructor(color) {
this.carColor = `${color} car`;
}
revealColor() {
console.log(`I have a ${this.carColor}`);
}
}

const myCarColor = new CarColor("white");

myCarColor.revealColor();

Try Editing It

The snippet above automatically invoked the constructor method while creating myCarColor's object instance.

Therefore, the computer processed the constructor's statements before executing the myCarColor.revealColor() code.

Note the following:

  • The constructor method automatically receives the arguments you pass to the class.
  • You can only use the JavaScript method shorthand technique to define a constructor. Otherwise, browsers will throw an Uncaught SyntaxError.
  • A class can have only one constructor method. Otherwise, browsers will throw an Uncaught SyntaxError.

Now that we know how to create class fields, we can discuss the available types.

Types of Class Fields

The three types of class fields are:

  • Public class fields
  • Private class fields
  • Static class fields

Let's discuss each type.

What is a public class field in JavaScript classes?

A public class field is a property you can access and modify from within and outside the class body.

tip

Although you can define multiple public class fields with the same name, the last field will overwrite the previous ones.

Example: How to create public class fields

// Define a JavaScript class:
class Name {
// Create two public class fields:
myName = "Oluwatobi";
updateMyName(name) {
this.myName = name;
}
}

// Create a new object instance:
const author = new Name();

// Check myName's current value:
author.myName;

// The invocation above will return: "Oluwatobi"

// Modify myName's value:
author.myName = "Sofela";

// Check myName's current value:
author.myName;

// The invocation above will return: "Sofela"

// Use Name's internal method to update myName's value:
author.updateMyName("CodeSweetly");

// Check myName's current value:
author.myName;

// The invocation above will return: "CodeSweetly"

Try Editing It

The Name class in the snippet above contains public class fields because you can modify the two properties from within and outside the class's body.

Suppose you define multiple public class fields with the same name. In that case, the last property will overwrite the previous ones.

Example: The last public class field overwrites the previous ones with the same name

// Define a JavaScript class:
class Name {
// Create three public class fields:
myName = "Oluwatobi";
myName = "Sofela";
myName = "CodeSweetly";
}

// Create a new object instance:
const author = new Name();

// Check myName's current value:
author.myName;

// The invocation above will return: "CodeSweetly"

Try Editing It

The snippet above returned "CodeSweetly" because the last myName public class field overwrites the previously declared ones.

What is a private class field in JavaScript classes?

A private class field is a property you can only access and modify within the class's body.

We prefix a class field with the hash (#) symbol to make it a private property.

tip

Private class field names must be unique. You cannot redeclare a private field in the same class. Otherwise, the browser will throw an Uncaught SyntaxError.

Example: How to create private class fields

// Define a JavaScript class:
class Name {
// Create a private class field:
#myName = "Oluwatobi";
}

// Create a new object instance:
const author = new Name();

// Check myName's current value:
author.myName;

// The invocation above will return: undefined

Try Editing It

The snippet above returned undefined because myName is a private class field you can only read and modify from within the class's body.

Therefore, you need to use an internal code to access myName.

Example: How to access private class fields

// Define a JavaScript class:
class Name {
// Create a private class field:
#myName = "Oluwatobi";

// Create a public class field:
fullName = `${this.#myName} Sofela`;

// Create another public class field:
showMyName() {
return this.#myName;
}
}

// Create a new object instance:
const author = new Name();

// Check fullName's current value:
author.fullName;

// The invocation above will return: "Oluwatobi Sofela"

// Check myName's current value:
author.showMyName();

// The invocation above will return: "Oluwatobi"

Try Editing It

note
  • A constructor() method can only be public. Browsers will throw an Uncaught SyntaxError if you define it as a private class field.
  • You cannot create private class fields later (outside the class's body). For instance, writing author.#wifeName = "Sarah" will throw an Uncaught SyntaxError.
  • Private class fields make data encapsulation possible in JavaScript classes.

What is a static class field in JavaScript classes?

A static class field is a property you can only access and modify directly from the class itself.

In other words, JavaScript interprets static fields as a class's own properties—not instance or prototypal properties.

Therefore, a class's instance or prototype object cannot access static class fields.

tip
  • Although you can define multiple static class fields with the same name, the last field will overwrite the previous ones.
  • JavaScript does not add static fields to the prototype property. They remain in the class's body as its own properties. So, they are ideal for properties you wish to avoid replicating across the class's instance objects.

We prefix a class field with the static keyword to make it a static property.

Example: How to create static class fields

// Define a JavaScript class:
class Name {
// Create a static class field:
static myName = "Oluwatobi";
}

// Create a new object instance:
const author = new Name();

// Check myName's current value:
author.myName;

// The invocation above will return: undefined

Try Editing It

The snippet above returned undefined because myName is a static class field you can only read and modify from the class itself, not through the class's instance.

In other words, you need to call myName on the class itself to read or modify it.

Example: How to access static class fields

// Define a JavaScript class:
class Name {
// Create a static class field:
static myName = "Oluwatobi";
}

// Check myName's current value:
Name.myName;

// The invocation above will return: "Oluwatobi"

Try Editing It

Suppose you define multiple static class fields with the same name. In that case, the last property will overwrite the previous ones.

Example: The last static class field overwrites the previous ones with the same name

// Define a JavaScript class:
class Name {
// Create static class fields:
static myName = "Oluwatobi";
static myName = "Sofela";
static myName = "CodeSweetly";
}

// Check myName's current value:
Name.myName;

// The invocation above will return: "CodeSweetly"

Try Editing It

The snippet above returned "CodeSweetly" because the last myName static class field overwrites the previously declared ones.

Static vs. Instance vs. Prototypal Class Fields

  • A static class field is the own property of the class.
  • An instance class field is a property JavaScript adds to the object the new keyword creates from the class.
  • A prototypal class field is a property JavaScript adds to the class's prototype chain.

Static vs. Instance vs. Prototypal Class Field Methods

  • A static class field method is a method (regular or shorthand) you can only access and modify directly from the class itself. It is the own property of the class.
  • An instance class field method is a regular method JavaScript adds to the object instance the new keyword creates from the class. It is the own property of the object instance.
  • A prototypal class field method is a shorthand method JavaScript adds to a class's prototype property. You can access and modify it through the prototype chain. It is the prototypal property of the class.

Overview

In this article, we discussed what a JavaScript class field is. We also used examples to discuss the three types.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article