Getters and Setters in JavaScript

Jeffrey Amen
Level Up Coding
Published in
3 min readJun 20, 2021

--

JavaScript code on screen By Pankaj Patel

Getters and Setters in JavaScript first appeared in 2009 with the release of ECMAScript 5. I initially came across them only briefly in The Complete JavaScript Course 2020 by Jonas Schmedtmann. There was a short chapter on Getters and Setters and honestly, I did not place too much importance on this topic. However, this year I am taking the Codecademy Pro pathway, Backend Software Engineer. This course covers full-stack JavaScript and places a heavy emphasis on using Getters and Setters. I had a difficult time resolving the difference in emphasis, so I went back and reviewed the documentation to get a better grasp of it.

W3Schools’ JavaScript tutorial calls Getters and Setters as “JavaScript Accessors” which allow you to define object accessors.

MDN JavaScript documentation gives a more descriptive definition.

Getter — binds an object property to a function that will be called when that property is looked up.

Setter — binds an object property to a function to be called when there is an attempt to set that property.

They give you a way of defining a property but do not calculate the property’s value until it is accessed. This defers the cost of calculating the value until needed. So, they allow the value to be dynamically calculated. (MDN)

Const person = {   firstName: ‘John’,   lastNamen: ‘Doe’,   language: ‘en’,   //Getter //
get lang() {
Return this.language; }, //Setter // set lang(lang){ this.language = lang; }}console.log(person.lang); // getter returns “en”person.lang = “esp”; // sets language to “esp”

Why do we need to use Getters and Setters? (per W3Schools)

  • Secure better data quality when using them
  • It gives a simpler syntax for the properties and methods of an object.
  • Useful for doing things behind the scenes.

Modifying a property using a Getter

const person = {   home: “California “,   get homeTown() {      return ‘San Francisco, ${this.home}’;
}
}console.log(person.hometown) // San Francisco, California

Two Different Perspectives

Jonas Schmedtmann: “Getters and Setters are nice to use sometimes but don’t need to be used, and many programmers don’t use them at all.”

Codecademy, on the other hand, used it in the context of privatizing object properties. However, their curriculum implied it was required or used routinely.

const person = {   _firstName: 'John', //underscore used by convention to mean property should not be altered.// Means property not intended to be manipulated directly   _lastName: 'Doe',   _age: 37,// getter allows property to be manipulated upon retrieval   get fullName() {      if (this._firstName && this._lastName)      return `${this._firstName} ${this._lastName}`;      } else {         return 'Missing a first name or a last name.';        }    },// setter allows manipulation of property prior to storage.    set age(newAge){       if (typeof newAge === 'number'){       this._age = newAge;     } else {        console.log('You must assign a number to age');       }     }};// To call the getter method:person.fullName; // 'John Doe'//to use setterperson.age = 40;console.log(person._age); // Logs: 40person.age = '40'; // Logs: You must assign a number to age

Getters and Setters are also used in Classes

class Dog {   constructor(name) {      this._name = name;      this._behavior = 0;   },   get name() {      return this._name;   },   get behavior() {      return this._behavior;   },   set name(newName){      this._name = newName;   },   incrementBehavior() {      this._behavior++;   }}

I can see how one would want to use Getters and Setters under this context. But are they absolutely necessary? Are there other circumstances where you would want to use them? Or are they just another redundancy in code?

I’d be interested in hearing what more experienced JavaScript programmers have to say about Getters and Setters.

--

--