Understanding JS getters and setters
Tags: javascript, oop, webdev, beginners
Published: 2024-05-26 16:26:31

Let's dive to understand getters and setters from a 10x newbie. You should have a basic knowledge of JavaScript objects and classes to go on with this tutorial.

## `get`
What is `get` in JavaScript?
`get` is a syntax that binds an object property to function, that will be called when that property is looked up.

### Using `get` in objects
```javascript
//  Object example with a getter
const obj = {
name: 'John',
surname: 'Doe',
age: 32,
get intro() {
return `Hello there, my name is ${this.name} and I am ${this.age} years old`;
  }
}

console.log(obj.intro) 
// OUTPUT: Hello there, my name is John and I am 32 years old
```
So a `get` is used to look into a function code and run it. Without the get syntax the output will be the whole function ` intro() { /* ... */}` because calling our `obj.intro` won't know what to do with our function call and hence it returns the whole function. 

* `get` can bind property names of the function. Example;
```javascript
const obj = {
/* code... */
get prop() { /* code to be executed when calling obj.prop */ }
}
```
* Also `get` can use computed property names (expression). Example;
```javascript
const obj = {
/* code... */
get [expression]() { /* code to be executed when calling obj.[expression] */ }
}
```

### Using `get` in classes
In classes `get` is used the same as in objects but since getter properties are defined on the `prototype` property of the class unlike in object you need to instantiate the class with the `new` keyword, otherwise calling raw class will return `undefined`. Example;
```javascript
class WithGet {
  text = "Hi there";
  
  get greeting() {
    return this.text;
  }
}

// Without instantiation
console.log(WithGet.greeeting)
// OUTPUT: undefined

// With instantiation
const greet = new WithGet()
console.log(greet.greeting) 
// OUTPUT: Hi there
```
That's it on understanding getters. Some advanced concepts on static and private getters, deleting a getter, defining a getter on an existing object are discussed [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get). 

* `get` is useful because it provides encapsulation, allowing you to control access to the internal properties of an object.
* `get` is used for lazy evaluation, where a value is only computed the first time it is accessed.
* `get` provide a clean and readable way to access properties.



## `set`
What is `set` in JavaScript?
`set` syntax binds an object property to a function to be called when there is an attempt to set that property.


### Using `set` in objects
```javascript
// Object example with a setter

const score = {
  sheet: [],
  set grade(passmark) {
    this.sheet.push(passmark);
  }
}

score.grade = 'A';
score.grade = 'B';

console.log(score.sheet);
// OUTPUT: ["A", "B"]
```
So a `set` is used to set put into a property some value defined in the setter eg. in our `score` object, `set` is used to put grades in the `sheet` array property. Without the setter `set` our code would run but it would return an empty array `[]` because the grade function method won't know what to do with sheet array property.

* `set` can bind a function method. Example;
```javascript
const obj = {
/* code... */
set prop(val) { /* code to be executed when calling obj.prop */ }
}
```
Where the `val` parameter is the value which you want to set on the object.

* Also `set` can use computed property names (expression). Example;
```javascript
const obj = {
/* code... */
get [expression](val) { /* code to be executed when calling obj.[expression] */ }
}
```


### Using `set` in classes
In classes `set` has the same syntax but commas are not needed between methods. Example;
```javascript
class WithSet {
  text = "Hi there";
  get greeting() {
    return this.text;
  }

  set greeting(name) {
     this.text = `Hello ${name}`;
  }
}

// Without instantiation
console.log(WithSet.greeting)
// OUTPUT: undefined

// With instantiation
const greet = new WithSet()
greet.greeting  = 'John';
console.log(greet.greeting) 
// OUTPUT: Hello John

```
**Note** In classes, to return the code which the setter (for this example `greeting` setter) has done action on, you need a getter otherwise, you need to explicitly define a function method that will return the greeting or use a constructor.

That's it on understanding setters. Some advanced concepts on static and private setters, deleting a setter, defining a setter on an existing object are discussed [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set).

* `set` allows you to control how properties of an object are modified thus offering control and encapsulation of code.
* `set` help maintain the integrity of the object's data by ensuring that any changes are validated and processed correctly before being applied.
* `set` centralize the logic for updating a property, which makes the code easier to maintain and refactor.

Thanks for reading this tutorial and I hope you understood what are getters and setters. For any queries, corrections or suggestion please comment so we can all level up to 10x newbies😉.