Home > Back-end >  How to check if a variable is a boolean type
How to check if a variable is a boolean type

Time:02-11

o = console.log(isNaN(c));
        if(o === false){
            console.log(33);
        }
        if(o === true){
            console.log(39)
        }

Is this the correct way to check if something is of a boolean value|??

CodePudding user response:

you can use typeof

 var typeCheck = true
 console.log(typeof typeCheck);
// expected output: "boolean" 

Here is the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

CodePudding user response:

Just check the type.

If Javascript would not have this feature, you could convert the value to boolean and check with strict comparison.

value === Boolean(value)

function isBoolean(value) {
    return typeof value === 'boolean';
}

console.log(isBoolean(1));
console.log(isBoolean(0));
console.log(isBoolean(true));
console.log(isBoolean(false));

  • Related