Objects - Setter & Getter - is my understanding correct?

Dear friends of JS development :slight_smile:

I assume to a certain level this.greeting :wink: also includes me, who would have that only days ago :smile: (but I digress)

I am working myself through the advanced JS syntax lessons about objects.

In this lesson, we talk about Setters and Getters
https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-objects/lessons/advanced-objects/exercises/setters

My question is this:
Is it correct that getters allow to retrieve information of an object in an easy way like this

myObject.myMethod

and setters allow to assign information?

The reason I’m asking is that I’m not 100% sure what the advantage of using these approaches is…

Maybe the community can help to un-confuse :grinning: me

Thank you!

this is true, but we can achieve the same thing with a regular property, so why do we need getters?

The getter and setter allow us to change the default behavior of a property:

const myObj = {
   _a: [],
   get a() {
       return this._a.join('-');
   },
   set a(aIn) {
      this._a.push(aIn);
   }
}

myObj.a = 3;
myObj.a = 4;
myObj.a = 5;

console.log(myObj.a);

we changed the representation of the property. Under the hood, the property is an array, but we now get a string.

we also changed the default assignment behavior, assigning to the property will now push the element into the array. We could expand the setter further by only allowing Numbers for example

4 Likes

I am sorry, but I still don’t get it, especially not from the code that you - thankfully - provided.

I have no clue what your code is doing here. I tried to go over it on my own (in VS Code), I tried searching the interwebs, I looked it up in books, but I still cannot understand what “getters and setters” are all about.

For example in your code, I see 2 ways that “a” is called. How does JS know, if it should use the getter or setter?? Or do they work together (I also re-read the text in the codecademy lessons and must admit, it does make things worse, as it is not very clear in explanation).

Getters and setters do work together, but, in the code @stetim94 gave, as in all code with getters/setters, the setter is called when you assign something to the variable:

and the getter is called when you attempt to use the variable (but not assign it):

The purpose of getters/setters is to give a certain variable qualities that perhaps make it easier to work with.
For example, in stetim94’s code, instead of doing myObj.a.push(number) every time you want to push a number to the a array, you can just go myObj.a = number ; setters allow you to do things under the hood, which makes using the object’s properties a lot easier.

Getters, on the other hand, allow the output(for lack of a better word) of the variable to be as you want in returned from the object. Take stetim94’s example, perhaps you want a's value to be a string, yet we want it mutable and so forth-so we want to be able to get all of the functionality of an array, but with the return value of a string. This is where the getter comes in. It returns the value you want the property to return.
I hope this helps!

2 Likes

Thank you @codeneutrino

I think I understand the setters approach - to make my life easier and write less code

But this raises another question: If I distribute code that way, doesn’t it become clumsy and hard to “read” pretty fast?

For me myObj.a.push(number) is much clear to understand than myObj.a …

Regarding the getters, I still don’t get it. What does “the output of the variable to be as you want in returned from the object” mean?

I am sorry, but I really have a difficult time understanding this.

Maybe, but if you’ve got a more complex object, it might be easier for the programmer (and perhaps even more memory efficient).

Getters:
If you have an object with a property (a) which stores an array, because you need it to be mutable, and have other properties of an array. But, you want to use it as a string when call the property(myObj.a) should return a string. You could do this in the program:

myObj.a.join('-');

However, you could do that within the object, in a getter:

myObj = {
 _a: [],
 get a(){
  return this._a.join("-");
 }
}
console.log(myObj.a);

Although this may look a longer way to do it, it means you have more functionality within the object itself, and it means if you’re importing the object, your code can be cleaner.

Are we talking about modularity here, meaning making code more modular and reusable? Maybe I’m just looking at it from the wrong perspective?

Yes. If you have more code built into the object, it means it is more reusable for not only yourself, but for others to also use it as a module.

1 Like

aaaahhhh, now that makes it clearer. It’s a little bit like CSS, I keep it in one place, modularize it so I can re-use it later, rather than writing it out every single time…

1 Like

it is, i merely wanted to demonstrated that we have more control over the behavior a property using setters, so much even that we can change the assignment behavior.

if you change the default assignment behavior, would need to be documented. Otherwise you look at the code later (or another developer) and they are like: What happened here?

one of the first rules of programming: Don’t Repeat Yourself (DRY). Objects (function, and more) can be exported, to be used by other scripts. Allowing you to organize your code

objects are not only modular, we can also use them to group certain functionality. If we had a car object, we could give this object methods like drive and refuel.

once your code base starts to grow, this kind of code organization for readability and maintainability becomes really important.

1 Like

Person with the same level of confusion here.

To my understanding the whole Getter & Setter thing is to…

  • since get and set can use the same method name it is more standardized (I could achieve the same thing with 2 different methods)
  • make it feel like you are assigning properties to an object
  • while the get/set method in the back takes care of how values can be assigned back to the properties

Can anyone confirm that?

I think the exercise don’t do a good job of explaining the potential of getters and setters, if we look at the MDN documentation we see the following example:

const obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    if (this.log.length === 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
};

console.log(obj.latest);

where we use a getter to create a property with “complicated” logic.

Or we can do something along these lines:

const myObj = {
  _myArr: [],
  get myArr() {
     return this._myArr.join();
  },
  set myArr(valIn) {
    this._myArr.push(valIn);
  }
}

myObj.myArr = 1;
myObj.myArr = 2;
myObj.myArr = 3;

console.log(myObj.myArr);

Under the hood, the property is an array, but we treat it as string (getter) and push elements to the array (change default assignment behavior)

part of getters and setters is clarity and readability. If another developer takes over your code, its easier for the new developer to understand they have to use the getters and setters for the property. With a method, this might not be equally clear.

1 Like

Ok, I think I understood.

But this means I could also write 2 methods like this:

const myObj = { _myArr: [], getMyArr() { return this._myArr.join(); }, setMyArr(valIn) { this._myArr.push(valIn); } } myObj.setMyArr(1); myObj.setMyArr(2); myObj.setMyArr(3); console.log(myObj._myArr);

The Endresult would be the same, but in terms of readability and another developer making sense of the code I wrote, it is better to use get / set?

How you get the result can also be important

well, I didn’t want to go down this path, but I suppose I have to in order to answer your question

One of the problems here is that JavaScript doesn’t enforce proper encapsulation. Which really takes value away from getters and setters

we can still manipulate _myArr, there is no way to enforce private or protected. Which is very unfortunate.

As a result, I am less convinced by this (getters and setters) concept as a whole in JavaScript

1 Like