432

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?

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154

18 Answers18

799

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

if (typeof variable == "boolean") {
    // variable is a boolean
}
Roman Snitko
  • 3,655
  • 24
  • 29
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 10
    It's not clear what the OP is trying to do, but capital-B Boolean objects give "object" as their type via `typeof`. – Pointy Mar 02 '15 at 16:27
  • @Pointy from OP's comment on Satpal's answer(now deleted) asks for what I intepreted I suppose. – Amit Joki Mar 02 '15 at 16:29
  • 29
    1) `typeof` is not a function. 2) Using the triple operator === with `typeof` is not required, since it will return always a string (afaik, but as far as I remember, there was another case for some very old browsers). 3) `typeof` and string comparisons are slow. Don't use them. Check directly with `(variable === true || variable === false)` (I suggest to write a function). – StanE Jul 10 '16 at 16:56
  • 8
    wouldn't `typeof(variable) === typeof(true)` be more robust? – Marcus Junius Brutus Nov 08 '16 at 16:37
  • `var name = true console.log(typeof(name)) ` why the output is `string` ? – Tushar Niras Dec 30 '16 at 06:35
  • 2
    @TusharNiras `name` is a global window property with a special *getter* https://developer.mozilla.org/en-US/docs/Web/API/Window/name – Zach Lysobey Dec 05 '17 at 22:03
  • @Zach Lysobey true.. resolved long back... thanks anyway – Tushar Niras Dec 06 '17 at 04:42
  • 4
    @MarcusJuniusBrutus @AmitJoki that's nonsense, there is no advantage in using more verbose `typeof true` instead of `"boolean"`. New versions ECMAScript will never have any breaking changes. – m93a Feb 23 '19 at 21:49
  • @MarcusJuniusBrutus is boolean spelt wit a capital B? In english is it boolean or booleen? – cquezel May 14 '20 at 14:51
73

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.

Alireza
  • 100,211
  • 27
  • 269
  • 172
  • 1
    Disagree: `new Boolean(true) === new Boolean(true)` should return false (as references are different). That's why the `isBoolean(new Boolean(true))` will say **false** while it must be **true** ( `new Boolean(true)` is of type *boolean*). – AlexMelw Feb 07 '20 at 10:21
  • How do you type val? export const isBoolean = (val: ???): boolean => "boolean" === typeof val – FloodGames Jun 27 '21 at 21:02
47

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 3
    It doesn't seem very practical to me to treat Boolean primitives and Boolean objects as the same, because I can't use them in the same way anyway. – Felix Kling Mar 02 '15 at 16:40
  • @FelixKling - doesn't seem very practical to me either, but it seems like the OP is trying to determine if a variable is a boolean, even when created with `new Boolean()`, which techically isn't a boolean, but an object, but still holds a boolean value. – adeneo Mar 02 '15 at 16:43
  • I think the OP just didn't know that `new Boolean()` returns an object (see comments on question). But whatever :) – Felix Kling Mar 02 '15 at 16:44
  • @FelixKling - Just reread the question and comments, and I see now that the OP is basically trying to do `typeof variable === typeof new Boolean()` and probably just want a regular typeof check, but somehow got caught up in some strange jQuery syntax instead. – adeneo Mar 02 '15 at 16:46
  • Depending on how resilient you want to make your code, if the `bool` param passed in was `null` the `typeof bool === 'object'` would still evaluate and a `TypeError: Cannot read property 'valueOf' of null` exception would be thrown on the call to `typeof bool.valueOf()`. Thus, I would change that last line to read: `(typeof bool === 'object' && bool && typeof bool.valueOf() === 'boolean');` which will evaluate only when `bool` is *not* null. – Al Dass Sep 26 '17 at 14:27
26

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;
    }
    
iSkore
  • 7,394
  • 3
  • 34
  • 59
  • Why is type coersion "most optimal"? Is it faster or more readable than `typeof`? I highly doubt it. – m93a Feb 23 '19 at 21:59
  • So, in theory, coercing the value to a boolean does 1 coercion + 2 comparisons + 1 comparison. The first two comparisons are during the coercion steps, and the last comparison is against the first position (which is now a primitive). Doing `typeof` is also 1 coercion, but the `typeof` method does a few getters and comparisons inside + 1 comparison at the very end. [Here's the V8 reference for `typeof`](https://github.com/v8/v8/blob/e034c1ad9c44b146cd9b4fed54a900b2e4845976/src/compiler/simplified-lowering.cc#L391) – iSkore Feb 23 '19 at 23:29
  • 1
    After all, either method is so damn fast, the nanoseconds amount of difference is so small, it would be hard to even test out which was faster. Here are two JSPerf's. One says `!!` is faster, one says `Boolean` is faster. Just a reference to how small the delta is between tests. Boolean checks are fast. https://jsperf.com/bool-not-not https://jsperf.com/bool-vs-doublenot – iSkore Feb 23 '19 at 23:35
  • 1
    I agree that the difference is not measurable and in such case, readabilidy should AFAIK always go first. Thus the standard and comprehensible `typeof val === "boolean"` is optimal. – m93a Feb 24 '19 at 20:10
  • 1
    Yes, I agree with that. Readability is important. Operators aren't as readable - will update – iSkore Feb 24 '19 at 21:19
  • 1
    I think it would not be a problem to use the operators though. If they are wrapped in a function, that still makes it self-explanatory what you are trying to do. – Lucas Manzke Apr 09 '20 at 07:35
18

You can use pure JavaScript to achieve this:

var test = true;
if (typeof test === 'boolean')
   console.log('test is a boolean!');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Morry
  • 726
  • 4
  • 11
10

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;
}
Willem Franco
  • 854
  • 9
  • 7
6

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.

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
4

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
Steve
  • 4,372
  • 26
  • 37
4

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");
3LM0U5441F
  • 151
  • 1
  • 3
3

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

Volodymyr Frolov
  • 1,256
  • 5
  • 16
  • 25
  • Why would you want to return `"boolean"` if the value really is an object? That doesn't seem very practical to me. Boolean objects have to be dealt with differently than Boolean primitives anyway. – Felix Kling Mar 02 '15 at 16:38
  • 1
    The code isn't clean, pretty, or clear. Note the OP is asking for a "cleaner way to achieve this". – Spencer Wieczorek Mar 02 '15 at 16:44
  • I agree that the code isn't clean or pretty, but AFAIK there is no pretty and at the same time reliable option in case if both boolean primitives and Boolean objects at the scene. – Volodymyr Frolov Mar 02 '15 at 17:31
  • This seems like a seriously overkill solution to do something that can be done natively. – brandonscript Nov 28 '15 at 05:21
2

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

function isBoolean(value) {
  return typeof value === "boolean";
}
mhatch
  • 4,441
  • 6
  • 36
  • 62
2

Sometimes we need a single way to check it. typeof is 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...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

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

  • you need to recreate them in every project you are involved in
  • other developers might have different habits, or need to check the source of your function to see which impementation of check you use, to know what the weak points of your check are
  • you will be fruustrated when you will try to write one liner in the console on the 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    By the way, if performance is very very important, having a function to check for the boolean value took 10% more time in my tests than doing it inline (for-loop 100000000x) on Node.js. But the worst option was `v === true || v === false`, which does 2 verifications in case of `false`. Ranking: (1 - both praticaly the same) `typeof v === 'boolean` and `typeof v === typeof true`, (2) `isBoolean(v)`, (3) `v === true || v === false`. – jpenna May 03 '18 at 16:26
  • I disagree with this wholeheartedly. Different habits are the exact reason why: How often have I experienced bugs because everyone checked things differently? If you have one place to check for a boolean value, that is much preferable IMO to different-style checks all over the codebase. It is also much easier to consistently change the behavior of such a function. – Lucas Manzke Apr 09 '20 at 10:24
1
if(['true', 'yes', '1'].includes(single_value)) {
    return  true;   
}
else if(['false', 'no', '0'].includes(single_value)) {
    return  false;  
}

if you have a string

Denver
  • 11
  • 2
1
  • 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
TechWisdom
  • 3,960
  • 4
  • 33
  • 40
1

One more decision with es2015 arrow function

const isBoolean = val => typeof val === 'boolean';
Gor
  • 1,385
  • 12
  • 7
1

Update: The previous solution is more specific, you can choose which value you want to consider as a boolean and you can add that in regex, If you need a more general solution and don't want to add a library then check out the below solution(taken from lodash's boolean)

function getTag(value) {
  if (value == null) {
    return value === undefined ? '[object Undefined]' : '[object Null]'
  }
  return toString.call(value)
}

function isObjectLike(value) {
  return typeof value === 'object' && value !== null
}

function isBoolean(value) {
  return value === true || value === false ||
    (isObjectLike(value) && getTag(value) == '[object Boolean]')
}

Previous Solution

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>');
Sameer
  • 4,758
  • 3
  • 20
  • 41
0

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
Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54