const robot = { _model: '1E78V2', _energyLevel: 100, get energyLevel(){ if(typeof this._energyLevel === 'number') { return 'My current energy level is ' + this._energyLevel } else { return "System malfunction: cannot retrieve energy level" } } }; console.log(robot.energyLevel); /* Getters can perform an action on the data when getting a property. Getters can return different values using conditionals. In a getter, we can access the properties of the calling object using this. The functionality of our code is easier for other developers to understand. */
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter