JavaScript Mutators
Published Oct 21, 2023
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
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours