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(
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
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.
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;
}
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"
.
That's what typeof is there for. The parentheses are optional since it is an operator.
if (typeof variable === "boolean"){
// variable is a boolean
}
There are three "vanilla" ways to check this with or without jQuery.
First is to force boolean evaluation by coercion, then check if it's equal to the original value:
function isBoolean( n ) {
return !!n === n;
}
Doing a simple typeof
check:
function isBoolean( n ) {
return typeof n === 'boolean';
}
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;
}