Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

what is getter and setter in javascript

// 1) In JavaScript, getter methods are used to access the properties of an object.
// we use get keyword to define a getter method to get or access the property value
const student = {
    // data property
    firstName: 'Chetan',
 
    // accessor property(getter)
    get getName() {
        return this.firstName;
    }
};

// accessing data property
console.log(student.firstName); // Chetan

// accessing getter methods or accessing the value as a property
console.log(student.getName); // Chetan

// trying to access as a method
console.log(student.getName()); // error

// In the above program, a getter method getName() is created to access the property of an object.
// Note: To create a getter method, the get keyword is used.

// 2) In JavaScript, setter methods are used to change the values of an object.
// we use set keyword to define a setter method to set the property value

const student = {
    firstName: 'Chetan',
    
    //accessor property(setter)
    set changeName(newName) {
        this.firstName = newName;
    }
};

console.log(student.firstName); // Chetan

// change(set) object property using a setter
student.changeName = 'Jeny';

console.log(student.firstName); // Jeny
// In the above example, the setter method is used to change the value of an object.
// Note: To create a setter method, the set keyword is used.
 
PREVIOUS NEXT
Tagged: #getter #setter #javascript
ADD COMMENT
Topic
Name
9+3 =