Created
May 27, 2022 10:53
-
-
Save akbarjondev/f15384e365ff88be932cf6e030dac528 to your computer and use it in GitHub Desktop.
A complete guide to check data types in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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