Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Created May 27, 2022 10:53
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 akbarjondev/f15384e365ff88be932cf6e030dac528 to your computer and use it in GitHub Desktop.
Save akbarjondev/f15384e365ff88be932cf6e030dac528 to your computer and use it in GitHub Desktop.
A complete guide to check data types in JavaScript
function getType(obj) {
const lowerCaseTheFirstLetter = (str) => str[0].toLowerCase() + str.slice(1);
const type = typeof obj;
if (type !== 'object') {
return type;
}
return lowerCaseTheFirstLetter(
Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1')
);
}
getType([]); // "array"
getType('123'); // "string"
getType(null); // "null"
getType(undefined); // "undefined"
getType(); // "undefined"
getType(function () {}); // "function"
getType(/123/g); // "regExp"
getType(new Date()); // "date"
getType(new Map()); // "map"
getType(new Set()); // "set"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment