Mihai Serban

Cluj-Napoca, Romania 🇷🇴

Software engineer in constant search for new and exciting technologies

Want to hire me for your next project? Get in touch.

ES6 cheatsheet  —  Getter and setter functions

Serban Mihai / 20 October 2018

~1 min read

ES6 getter and setter functions

ES6 has started supporting getter and setter functions within classes. Using the following example:

class Person {  
    constructor(name) {  
        this._name = name;  
    }  

    get name() {  
      if(this._name) {  
        return this._name.toUpperCase();    
      } else {  
        return undefined;  
      }    
    }  

    set name(newName) {  
      if (newName == this._name) {  
        console.log('I already have this name.');  
      } else if (newName) {  
        this._name = newName;  
      } else {  
        return false;  
      }  
    }  
}  

let person = new Person("John Doe");  

// uses the get method in the background  
if (person.name) {  
  console.log(person.name);  // John Doe  
}  

// uses the setter in the background  
person.name = "Jane Doe";  
console.log(person.name);  // Jane Doe

You can find a more complete ES6 cheetsheet on my Github page.

P.S. If you ❤️ this, make sure to follow me on Twitter, and share this with your friends 😀🙏🏻

gatsby  +  contentful  +  netlify  = ❤️[Source code]