Menu
Coddy logo textTech

Public & Private Class Fields

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 18 of 56.

In JavaScript classes, we can define two types of class fields: public and private.

Public fields are accessible from outside the class and can be used by anyone.

Create a class with public fields:

class Student {
  name = '';
  grade = 0;
  
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }
}

Create a student instance:

const student = new Student('Alice', 95);

Access public fields from outside the class:

console.log(student.name); // Output: "Alice"
student.grade = 98;
console.log(student.grade); // Output: 98

Private fields are denoted with the # symbol and can only be accessed from within the class:

class Student {
  name = '';
  #grade = 0;
  
  constructor(name, grade) {
    this.name = name;
    this.#grade = grade;
  }
  
  getGrade() {
    return this.#grade;
  }
  
  updateGrade(newGrade) {
    this.#grade = newGrade;
  }
}

Using private fields:

const student = new Student('Bob', 87);
console.log(student.name); // Output: "Bob"

// Access private field using a method
console.log(student.getGrade()); // Output: 87

// Update private field using a method
student.updateGrade(92);
console.log(student.getGrade()); // Output: 92

// This would cause an error:
// console.log(student.#grade); // SyntaxError
challenge icon

Challenge

  1. Add two fields into the class named UserAccount:
    1. A public field username
    2. A private field #password
  2. Add a constructor that takes username and password parameters

Cheat sheet

JavaScript classes support public and private fields.

Public fields are accessible from outside the class:

class Student {
  name = '';
  grade = 0;
  
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }
}

const student = new Student('Alice', 95);
console.log(student.name); // Output: "Alice"
student.grade = 98;

Private fields use the # symbol and can only be accessed within the class:

class Student {
  name = '';
  #grade = 0;
  
  constructor(name, grade) {
    this.name = name;
    this.#grade = grade;
  }
  
  getGrade() {
    return this.#grade;
  }
  
  updateGrade(newGrade) {
    this.#grade = newGrade;
  }
}

const student = new Student('Bob', 87);
console.log(student.getGrade()); // Output: 87
student.updateGrade(92);
// student.#grade would cause a SyntaxError

Try it yourself

import { UserAccount } from './userAccount.js';

// Test code - don't modify
const user = new UserAccount("alice", "secret123");
console.log(user.username);          // Should output "alice"

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming