Getter and Setter Creating with Object Literals in Javascript

Last Updated: September 20, 2017

As you know Javascript objects can be created as object literals. Now I am going to add getter and setter functionality to the object.

I have created product with name and price property and I have added getter and setter for the name property

var product={
    name:"",
    price:0,

    get getName(){
        return name
    },
    set setName(value){
        this.name=value
    }
}

product.setName="Fanta"
console.log(product.getName)
  • In Line 5 : You can see the getter for the name property
  • In Line 8 : You can see the setter for the name property