'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 1:[1]

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

Solution 2:[2]

Just like you did with the number variable, you can achieve same with _energyLevelvariable:

if(typeof(this._energyLevel) === typeof(number)){

Solution 3:[3]

I hope that helps

 var value = 11;
 if (typeof value == 'number') {
    // is a number
 } else {
    // is not a number
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MORÈ
Solution 2 Mantofka
Solution 3 ptrck