DEV Community

Justice Otuya
Justice Otuya

Posted on

Why should I use a getter and setter function instead of regular functions in a javascript Class?

I am reading about Object oriented programming and i am at a loss why i should use getters and setters instead of just regular functions.

take this code for example

class Stack {
    constructor(){
        this.stack = []
    }

   ...
    get lengthWithSetter(){
        console.log('length')
    }

    lengthWithFunction(){
        console.log('length')
    }

}
Enter fullscreen mode Exit fullscreen mode

const newStack = new Stack()

to call the lengthWithSetter method (accessor)

i can call it like this

newStack.lengthWithSetter
Enter fullscreen mode Exit fullscreen mode

while calling the lengthWithFunction method while calling the lengthWithSetter with

newStack.lengthWithFunction()
Enter fullscreen mode Exit fullscreen mode

my question is since newStack.lengthWithFunction() is consistent and has the structure of calling a normal function, while then do we have getters and setters.

because reading a code with getters and setters make it seem like they are properties and not methods (don't slander me for this).

So please can someone help answer this question, why do we need getters and setters when we can use regular functions

Top comments (0)