Skip to content

Instantly share code, notes, and snippets.

@rgchris
Last active April 2, 2021 04:54
Show Gist options
  • Save rgchris/177e70ee3cf1696f13410a49df95783e to your computer and use it in GitHub Desktop.
Save rgchris/177e70ee3cf1696f13410a49df95783e to your computer and use it in GitHub Desktop.
A type-checking function in JavaScript
window.istype = function(value, explicit = false) {
let type = Object.prototype.toString.apply(value).match(
/\[object ([A-Za-z_0-9]+)\]/
)[1]
switch (type) {
case "Boolean":
case "String":
case "BigInt":
case "Undefined":
case "Null":
case "Symbol":
case "Array":
case "Date":
case "RegExp":
case "Function":
case "Error":
break
case "Number":
if (!Number.isFinite(value)) type = Number.isNaN(value)
? "NaN"
: "Infinity"
break
default:
if (!explicit) type = "Object"
}
return type
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment