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