Ad Code

Responsive Advertisement

Can getters and setters have the same name JavaScript?

 In JavaScript, methods and variables can be written in the same way, so they may be confused. To avoid this, an underscore was added between the getter and setter in the getter-setter model. The getter is the method that returns the value of the variable, and the setter is the method that sets the value of the variable. It is very common in JavaScript to find variables that use this naming convention.

Can getters and setters have the same name JavaScript?

For example, if we have a variable named “age”, then the getter will be “get” and the setter will be “setAge”. We can also use the getter-setter model when we have a method that contains several variables. It is better to declare variables at the start of a method and then assign a value to them at the end of the method. It should be noted that the getter-setter model is rarely used in JavaScript in recent years, so it is not recommended to use it.

It is not a good practice in programming to have getters and setters having the same name. But it is not a problem for JS. In JS, Getter and Setter are two different functions. They are called in a different ways. When you are creating a class in JS, you will have to define it in the following way:

You are not allowed to use the same name for getter and setter. Getters and setters are considered two different objects in JavaScript. In part, it is because of the prototype chain that JavaScript uses. A good practice is to always use capital letters in the getters and setters to distinguish the extension objects in JavaScript.

example for Setters and Getters Names with Properties

If you implement the getters and setters in the following ways:

const main = {
  _name: {
     menus: [],
  },
  get menus(){
     return this._courses.menus;
  }
}

and


console.log(main.menus)

Setter and getter

You can create practical shortcuts for gaining access to and changing data inside an object using getters and setters. This can generally be thought of as an alternative to using two functions with an object to get and set a value, as in:

function main {
  var value;

  this.getValue = function() {
    return value;
  }

  this.setValue = function(val) {
    value = val;
  }

}

Post a Comment

0 Comments

Ad Code

Responsive Advertisement