How to check if type is Boolean

JavascriptJqueryTypes

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

With pure JavaScript, you can just simply use typeof and do something like typeof false or typeof true and it will return "boolean"...

But that's not the only way to do that, I'm creating functions below to show different ways you can check for Boolean in JavaScript, also different ways you can do it in some new frameworks, let's start with this one:

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

Or one-line ES6 way ...

const isBoolean = val => 'boolean' === typeof val;

and call it like!

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 like this:

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

In React, if using propTypes, you can check a value to be boolean like this:

MyComponent.propTypes = {
  children: PropTypes.bool.isRequired
};

If using TypeScript, you can use type boolean also:

let isDone: boolean = false;

Also another way to do it, is like converting the value to boolean and see if it's exactly the same still, something like:

const isBoolean = val => !!val === val;

or like:

const isBoolean = val => Boolean(val) === val;

and call it!

isBoolean(false); //return true

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

  1. First 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;
      }
    

Solution 5 - Javascript

You can use pure Javascript to achieve this:

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

Solution 6 - Javascript

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

Solution 7 - Javascript

BENCHMARKING:

All pretty similar...

const { performance } = require('perf_hooks');

const boolyah = true;
var t0 = 0;
var t1 = 0;
const loops = 1000000;
var results = { 1: 0, 2: 0, 3: 0, 4: 0 };

for (i = 0; i < loops; i++) {

	t0 = performance.now();
	boolyah === false || boolyah === true;
	t1 = performance.now();
	results['1'] += t1 - t0;

	t0 = performance.now();
	'boolean' === typeof boolyah;
	t1 = performance.now();
	results['2'] += t1 - t0;

	t0 = performance.now();
	!!boolyah === boolyah;
	t1 = performance.now();
	results['3'] += t1 - t0;

	t0 = performance.now();
	Boolean(boolyah) === boolyah;
	t1 = performance.now();
	results['4'] += t1 - t0;
}

console.log(results);

  // RESULTS
  // '0': 135.09559339284897,
  // '1': 136.38034391403198,
  // '2': 136.29421120882034,
  // '3': 135.1228678226471,
  // '4': 135.11531442403793

Solution 8 - Javascript

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".

Solution 9 - Javascript

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.

Solution 10 - Javascript

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

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

Solution 11 - Javascript

Sometimes we need a single way to check it. typeof not working for date etc. So I made it easy by

Date.prototype.getType() { return "date"; }

Also for Number, String, Boolean etc. we often need to check the type in a single way...

Solution 12 - Javascript

Creating functions like isBoolean which contains oneliner typeof v === "boolean" seems very unhandy in long term. i am suprised that almost everyone suggest to create your own function. It seems to be same cancer as extending native prototypes.

  • you need to recreate them in every project you are involved
  • other developers might have different habits,, or need to check source of your function to see which impementation of check you use, to know what are weak points of your check
  • you will be fruustrated when you will try to write one liner in console on site which doesn't belong to your project

just memoize typeof v === "boolean" and that's all. Add a template to your IDE to be able to put it by some three letter shortcut and be happy.

Solution 13 - Javascript

if(['true', 'yes', '1'].includes(single_value)) {
	return  true;	
}
else if(['false', 'no', '0'].includes(single_value)) {
	return  false;	
}

if you have a string

Solution 14 - Javascript

  • The most readable: val === false || val === true.

  • Also readable: typeof variable == typeof true.

  • The shortest, but not readable at all: !!val === val.

    Explanation:

  • [!!] The double exclamation mark converts the value into a Boolean.

  • [===] The triple equals test for strict equality: both the type (Boolean) and the value have to be the same.

  • If the original value is not a Boolean one, it won't pass the triple equals test. If it is a Boolean variable, it will pass the triple equals test (with both type & value).

    Tests:

  • !!5 === 5 // false

  • !!'test' === 'test' // false

  • let val = new Date(); !!val === val // false

  • !!true === true // true

  • !!false === false // true

Solution 15 - Javascript

In nodejs by using node-boolify we can use isBoolean();

        var isBoolean = require('node-boolify').isBoolean;
        isBoolean(true); //true
        isBoolean('true'); //true
        isBoolean('TRUE'); //false
        isBoolean(1); //true
        isBoolean(2); //false
        isBoolean(false); //true
        isBoolean('false'); //true
        isBoolean('FALSE'); //false
        isBoolean(0); //true
        isBoolean(null); //false
        isBoolean(undefined); //false
        isBoolean(); //false
        isBoolean(''); //false

Solution 16 - Javascript

One more decision with es2015 arrow function

const isBoolean = val => typeof val === 'boolean';

Solution 17 - Javascript

const isBoolean = (val) => {
  const boolValuesRegex = /true|false/; // Add other /true|false|1|0|on|off/
  if (val === undefined || val === null) return false;
  return boolValuesRegex.test(val.toString().toLowerCase());
}

const values = [true, false, 'true', 'false', 'TRUE', 'FALSE', 'sampletext', 1, undefined, null, (() => {}), {}, []];
document.body.innerHTML = values.map(x => `${x} - ${isBoolean(x)}`).join('</br>');

Solution 18 - Javascript

the easiest way to check for true and false is : (typeof value === "boolean") , but if value is an instance of the Boolean class, then it will return "object". so to handle that we must add another condition to check if : (value instanceof Boolean)

the code snippet :

const value = false;
//const value = new Boolean(10);
//const value = new Boolean("hi");

if((typeof value === "boolean") || (value instanceof Boolean))
	console.log("boolean");
else
	console.log("not boolean");

Solution 19 - Javascript

The approach of typeof == 'boolean' is okay, but here's another guaranteed way of doing it:

if(x === true || x === false)

you can write a function for this, ex:

function isBool(val){
   if(x === true || x === false) return true
   else return false
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatias CiceroView Question on Stackoverflow
Solution 1 - JavascriptAmit JokiView Answer on Stackoverflow
Solution 2 - JavascriptAlirezaView Answer on Stackoverflow
Solution 3 - JavascriptadeneoView Answer on Stackoverflow
Solution 4 - JavascriptiSkoreView Answer on Stackoverflow
Solution 5 - JavascriptMorryView Answer on Stackoverflow
Solution 6 - JavascriptWillem FrancoView Answer on Stackoverflow
Solution 7 - JavascriptSteveView Answer on Stackoverflow
Solution 8 - JavascriptVolodymyr FrolovView Answer on Stackoverflow
Solution 9 - JavascriptMarcus Junius BrutusView Answer on Stackoverflow
Solution 10 - JavascriptMohsen KadouraView Answer on Stackoverflow
Solution 11 - JavascriptImam KuncoroView Answer on Stackoverflow
Solution 12 - JavascriptKamil OrzechowskiView Answer on Stackoverflow
Solution 13 - JavascriptDenverView Answer on Stackoverflow
Solution 14 - JavascriptTechWisdomView Answer on Stackoverflow
Solution 15 - JavascriptRatan Uday KumarView Answer on Stackoverflow
Solution 16 - JavascriptGorView Answer on Stackoverflow
Solution 17 - JavascriptSameerView Answer on Stackoverflow
Solution 18 - Javascript3LM0U5441FView Answer on Stackoverflow
Solution 19 - JavascriptNormalView Answer on Stackoverflow