Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created July 5, 2023 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/f0e7bb90381ef5ad28cbe336a1f40cf6 to your computer and use it in GitHub Desktop.
Save cferdinandi/f0e7bb90381ef5ad28cbe336a1f40cf6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>getType()</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
/**
* More accurately check the type of a JavaScript object
* (c) Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {Object} obj The object
* @return {String} The object type
*/
function getType (obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
let arr = trueTypeOf([]); // array
let obj = trueTypeOf({}); // object
let str = trueTypeOf(''); // string
let date = trueTypeOf(new Date()); // date
let num = trueTypeOf(1); // number
let fn = trueTypeOf(function () {}); // function
let reg = trueTypeOf(/test/i); // regexp
let bool = trueTypeOf(true); // boolean
let nl = trueTypeOf(null); // null
let undef = trueTypeOf(); // undefined
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment