18

Getters and Setters

In this Chapter

  • Learn the difference between data properties and accessor properties

  • Learn about getters and setters

  • Identify when to use an accessor property versus a data property

The properties we have been working with so far are known as data properties. We give these properties a name and assign a value to them:

let foo = {
  a: "Hello",
  b: "Monday";
}

To read back the value, all we do is just access it directly:

console.log(foo.a);

Writing a value to this property is sorta what we would expect as well:

foo.a = "Manic";

Outside of setting and reading a value, there really isn’t much more we can do. That is the sad tale of a data property. Now, as part of reading and writing properties, what if we had the ability ...

Get Javascript Absolute Beginner's Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.