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!
Maybe, but if you’ve got a more complex object, it might be easier for the programmer (and perhaps even more memory efficient).
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:
However, you could do that within the object, in a getter:
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.