Skip to content
Home » Program to Get the Energy Level of a Robot

Program to Get the Energy Level of a Robot

In this program, we will be discussing how to implement a getter method to retrieve the energy level of a robot. The program uses JavaScript and demonstrates the usage of getters to perform actions on data.

Code

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.
*/

Code Explanation

The provided code snippet defines a robot object with two properties: _model and _energyLevel. The _energyLevel property holds the energy level of the robot, and the getter energyLevel is used to retrieve this value.

Inside the getter energyLevel, there is a conditional statement that checks if the _energyLevel is of type number. If it is, the getter returns a string indicating the current energy level of the robot. If it is not a number, the getter returns a string indicating a system malfunction.

To access the properties of the calling object, the keyword “this” is used. In this case, “this._energyLevel” is used to refer to the _energyLevel property of the robot object.

Finally, the program logs the call of the energyLevel getter using console.log(robot.energyLevel) to display the energy level of the robot.

Example:

Consider the following example:

javascript
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);

Output:

The output of the program will be: “My current energy level is 100”.

Conclusion

Using getters in JavaScript allows us to perform actions on data when retrieving properties. This can be especially useful when working with complex objects that require additional logic or validation. By using getters, the functionality of our code becomes easier for other developers to understand and maintain.

Also checkout the following codes.


How to Use Setter Method in JavaScript to Assign Values to an Object Property – Program to Check and Set Age
Program to Create a Robot Factory and Make It Beep