Mutators

Published Oct 21, 2023
Contribute to Docs

A mutator method (also known as a setter) can be used to prevent direct modification of a member variable by creating a private variable . This method determines the behavior when assigning a value to those variables.

In Javascript, private member variables are prefixed using the # symbol, while mutators are created with the set keyword.

class Animal {
#name;
set name(name) {
this.#name = name;
}
}
const someAnimal = new Animal();

The value of the private variable can now be updated by assigning a new value.

Note: The value of the private variable can not be retrieved without an accessor (also known as a getter).

class Animal {
#name;
set name(name) {
this.#name = name;
}
}
const someAnimal = new Animal();
someAnimal.name = 'Buddy';
console.log(someAnimal.name);

The example above results in the following output:

undefined

Attempts to access a private variable using the # prefix will result in a syntax error.

class Animal {
#name;
set name(name) {
this.#name = name;
}
}
const someAnimal = new Animal();
someAnimal.name = 'Buddy';
console.log(someAnimal.#name);

The example above results in the following output:

SyntaxError: Private field '#name' must be declared in an enclosing class

Codebyte Example

This example shows how to update and retrieve the value of a private variable.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy