Search code examples
javascriptjavascript-objects

What is an unnamed getter and setter in JavaScript? What are they used for?


I know that in JavaScript, an object may contain getters and setters:

const myObj = {
  get value() { return 'foo' },
  set value(val) { this. y = val }
}
console.log(myObj.value) // Outputs: "foo"
myObj.value = 'bar'
console.log(myObj.y) // Outputs: "bar"

But I see the next syntax is allowed in a plain JavaScript too:

const myObj = {
  get() { return 'foo' },
  set(val) { this.y = val }
}

But I don't understand how to access those functions, and which cases they are used for?


Solution

  • Many people may be confused about this, but the get and set methods in the example you provided are only regular object methods (properties), they are not getter and setter properties.

    const myObj = {
      get() { return 'foo' },
      set(val) { this.y = val }
    }
    console.log(myObj.get());  // Outputs: "foo"
    myObj.set("bar");
    console.log(myObj.y);  // Outputs: "bar"
    

    You can see here the valid object properties.