Last active
October 3, 2025 18:53
-
-
Save idettman/5c8eb3fd1551e46ef62354252a1e8810 to your computer and use it in GitHub Desktop.
Get Object Type using Object.toString()
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 type = Object.prototype.toString.call(obj); | |
| // toString returns '[object <type>]' | |
| // I only want the <type> value, so skip '[object ' chars and ending ']' char | |
| return type.substring(7, type.length-1); | |
| } | |
| const tests = [ | |
| 'str: ' + getType('foobar'), | |
| 'num: ' + getType(10), | |
| 'obj: ' + getType({greeting: 'hello'}), | |
| 'arr: ' + getType([0, 1, 2]), | |
| 'date: ' + getType(new Date()), | |
| 'el: ' + getType(document.createElement('p')), | |
| 'empty:' + getType(null), | |
| 'window: ' + getType(window), | |
| 'document: ' + getType(window.document), | |
| 'document first child: ' + getType(window.document.firstChild), | |
| 'document last child: ' + getType(window.document.lastChild), | |
| 'body: ' + getType(window.document.body) | |
| ]; | |
| const testsOutput = document.createElement('div'); | |
| testsOutput.style.whiteSpace = 'pre'; | |
| testsOutput.textContent = tests.join('\n'); | |
| document.body.appendChild(testsOutput); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment