Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading