Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Last active July 11, 2020 13:41
Show Gist options
  • Save shawndumas/6194339 to your computer and use it in GitHub Desktop.
Save shawndumas/6194339 to your computer and use it in GitHub Desktop.
Type Checking in JavaScript
function checkType (obj, typ) {
typ = ((typ && typ.toLowerCase()) || false);
var objTyp = Object
.prototype
.toString
.call(obj)
.replace('[object ', '')
.replace(']', '')
.toLowerCase();
return (typ) ? objTyp === typ : objTyp;
};
/*
checkType(new String()); // => "string"
checkType(new String(), 'string'); // => true
checkType(new Date()) // => "date"
checkType(new Date(), 'date') // => true
checkType([]); // => "array"
checkType([], 'array'); // => true
checkType(function () {}); // => "function"
checkType(function () {}, 'function'); // => true
checkType({}); // => "object"
checkType({}, 'object'); // => true
checkType(1); // => "number"
checkType(1, 'number'); // => true
checkType(''); // => "string"
checkType('', 'string'); // => true
checkType([]); // => "array"
checkType([], 'array'); // => true
checkType(window); // => "global"
checkType(window, 'global'); // => true
checkType(undefined); // => "undefined"
checkType(undefined, 'undefined'); // => true
checkType(null); // => "null"
checkType(null, 'null'); // => true
checkType(NaN); // => "number"
checkType(NaN, 'number'); // => true
checkType(true); // => "boolean"
checkType(true, 'boolean'); // => true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment