Home » Javascript » How to check if type is Boolean

How to check if type is Boolean

Posted by: admin November 29, 2017 Leave a comment

Questions:

How can I check if a variable’s type is of type Boolean?

I mean, there are some alternatives such as:

if(jQuery.type(new Boolean()) === jQuery.type(variable))
      //Do something..

But that doesn’t seem pretty to me.

Is there a cleaner way to achieve this?

Answers:

That’s what typeof is there for. The parentheses are optional since it is an operator.

if(typeof(variable) === "boolean"){
  // variable is a boolean
}

Questions:
Answers:

If you just want to check for a primitive value

typeof variable === 'boolean'

If for some strange reason you have booleans created with the constructor, those aren’t really booleans but objects containing a primitive boolean value, and one way to check for both primitive booleans and objects created with new Boolean is to do :

function checkBool(bool) {
    return typeof bool === 'boolean' || 
           (typeof bool === 'object' && 
            bool !== null            &&
           typeof bool.valueOf() === 'boolean');
}
function checkBool(bool) {
    return typeof bool === 'boolean' || 
           (typeof bool === 'object' && 
            bool !== null            &&
           typeof bool.valueOf() === 'boolean');
}

console.log( checkBool( 'string'          )); // false, string
console.log( checkBool( {test: 'this'}    )); // false, object
console.log( checkBool( null              )); // false, null
console.log( checkBool( undefined         )); // false, undefined
console.log( checkBool( new Boolean(true) )); // true
console.log( checkBool( new Boolean()     )); // true
console.log( checkBool( true              )); // true
console.log( checkBool( false             )); // true

Questions:
Answers:

You can use pure Javascript to achieve this:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');

Questions:
Answers:

The most reliable way to check type of a variable in JavaScript is the following:

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
toType(new Boolean(true)) // returns "boolean"
toType(true); // returns "boolean"

The reason for this complication is that typeof true returns "boolean" while typeof new Boolean(true) returns "object".

Questions:
Answers:

I would go with Lodash: isBoolean checks whether the passed-in variable is either primitive boolean or Boolean wrapper object and so accounts for all cases.

Questions:
Answers:

With pure JavaScript, just simply do this:

function isBoolean(val) {
   return val === false || val === true;
}

and call it!

isBoolean(false); //return true

also in Underscore source code they check it like this(with the _. at the start of the function name):

isBoolean = function(obj) {
   return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};

Also in jQuery you can check it as below:

jQuery.type(true); //return "boolean"

It’s recommended not using any framework for this as it’s really a simple check in JavaScript.

Questions:
Answers:

If you want your function can validate boolean objects too, the most efficient solution must be:

function isBoolean(val) {
  return val === false || val === true || val instanceof Boolean;
}

Questions:
Answers:

There are three “vanilla” ways to check this with or without jQuery.

  1. First, and probably most optimal, is to force boolean evaluation by coercion, then check if it’s equal to the original value:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  2. Doing a simple typeof check:

    function isBoolean( n ) {
        return typeof n === 'boolean';
    }
    
  3. Doing a completely overkill and unnecessary instantiation of a class wrapper on a primative:

    function isBoolean( n ) {
        return n instanceof Boolean;
    }
    

The third will only return true if you create a new Boolean class and pass that in.

To elaborate on primitives coercion (as shown in #1), all primitives types can be checked in this way:

  • Boolean:

    function isBoolean( n ) {
        return !!n === n;
    }
    
  • Number:

    function isNumber( n ) {
        return +n === n;
    }
    
  • String:

    function isString( n ) {
        return ''+n === n;
    }
    
Questions:
Answers:

You can create a function that checks the typeof for an argument.

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