How to check if type is Boolean

前端 未结 16 1745
深忆病人
深忆病人 2020-12-07 10:09

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(         


        
相关标签:
16条回答
  • 2020-12-07 10:32

    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

    0 讨论(0)
  • 2020-12-07 10:33

    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.

    0 讨论(0)
  • 2020-12-07 10:35

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

    function isBoolean(value) {
      return typeof value === "boolean";
    }
    
    0 讨论(0)
  • 2020-12-07 10:35

    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
    
    0 讨论(0)
  • 2020-12-07 10:38

    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.

    0 讨论(0)
  • 2020-12-07 10:39

    One more decision with es2015 arrow function

    const isBoolean = val => typeof val === 'boolean';
    
    0 讨论(0)
提交回复
热议问题