Java Script: How to check if value is number with typeof operator

How do I check in the if statement if _energyLevel is a number?
I need to use the typeOf operator for that.
Thanks for your help 🙂

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
    get energyLevel(){
      if(this._energyLevel === typeof(number)){
        return `My current energy level is ${_energyLevel}`
      }else{

      }
    }
};

>Solution :

typeof operator is applied whose type you want to find. In your case it will go with this._energyLevel and typeof returns type as string.

so better code will be

const robot = {
    _model: '1E78V2',
    _energyLevel: 100,
    get energyLevel() {
        if (typeof this._energyLevel === "number") {
            return `My current energy level is ${this._energyLevel}`
        } else {
            return 'Low battery'
        }
    }
};

console.log(robot.energyLevel);

Leave a Reply