[javascript] How to check if type is Boolean

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

_x000D_
_x000D_
function checkBool(bool) {_x000D_
    return typeof bool === 'boolean' || _x000D_
           (typeof bool === 'object' && _x000D_
            bool !== null            &&_x000D_
           typeof bool.valueOf() === 'boolean');_x000D_
}_x000D_
_x000D_
console.log( checkBool( 'string'          )); // false, string_x000D_
console.log( checkBool( {test: 'this'}    )); // false, object_x000D_
console.log( checkBool( null              )); // false, null_x000D_
console.log( checkBool( undefined         )); // false, undefined_x000D_
console.log( checkBool( new Boolean(true) )); // true_x000D_
console.log( checkBool( new Boolean()     )); // true_x000D_
console.log( checkBool( true              )); // true_x000D_
console.log( checkBool( false             )); // true
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean