Skip to main content

JavaScript Class Field Properties (Live Playground)

In this tutorial, we will learn about the class field properties in JavaScript, including public and private fields, and how to use them in your classes.

Public Fields

Public fields are properties that can be directly accessed and modified outside of the class. They can be declared directly within the class body, without using the constructor method.

Example:

class MyClass {
publicField = "I'm a public field";

displayField() {
console.log(this.publicField);
}
}

const myInstance = new MyClass();
myInstance.displayField(); // I'm a public field

You can also access and modify public fields directly:

const myInstance = new MyClass();
console.log(myInstance.publicField); // I'm a public field

myInstance.publicField = "I've been changed";
console.log(myInstance.publicField); // I've been changed
Live Playground, Try it Yourself

Private Fields

Private fields are properties that can only be accessed and modified within the class. To declare a private field, prefix the field name with a # symbol.

Example:

class MyClass {
#privateField = "I'm a private field";

displayField() {
console.log(this.#privateField);
}
}

const myInstance = new MyClass();
myInstance.displayField(); // I'm a private field

You cannot access or modify private fields directly:

const myInstance = new MyClass();
console.log(myInstance.#privateField); // SyntaxError: Private field '#privateField' must be declared in an enclosing class
Live Playground, Try it Yourself

Using Public and Private Fields Together

You can combine public and private fields to create a class with both public and private properties.

Example:

class MyClass {
publicField = "I'm a public field";
#privateField = "I'm a private field";

displayFields() {
console.log(`Public field: ${this.publicField}`);
console.log(`Private field: ${this.#privateField}`);
}
}

const myInstance = new MyClass();
myInstance.displayFields();
// Public field: I'm a public field
// Private field: I'm a private field
Live Playground, Try it Yourself

Conclusion

JavaScript class field properties offer a simple and expressive way to define public and private fields within your classes. By understanding how to use public and private fields, you can create more organized and encapsulated code, improving the structure and maintainability of your applications.