Member-only story

The Simplest Way to Use Getters and Setters in JavaScript Classes

Learn How to Effortlessly Control Access to Your Class Properties

Max N
3 min readApr 3, 2024

Getters and setters are special methods in JavaScript classes that allow you to control access to class properties. They provide a way to define computations or validations whenever a property is accessed or modified.

In this article, we’ll explore how to use getters and setters in JavaScript classes with clear, concise examples.

Let’s start with a simple example of a Person class:

class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
}

const person = new Person('Alice', 25);
console.log(person._name); // Alice
console.log(person._age); // 25

In this example, we have direct access to the _name and _age properties. However, it's generally considered good practice to use getters and setters to control access to these properties.

Here’s how we can add a getter and setter for the name property:

class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}

get name() {
return this._name;
}

set name(newName) {
// We can add validation or other logic here
this._name = newName;
}
}

const person =…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

Responses (1)