Skip to content

Instantly share code, notes, and snippets.

@idettman
Last active October 3, 2025 18:53
Show Gist options
  • Select an option

  • Save idettman/5c8eb3fd1551e46ef62354252a1e8810 to your computer and use it in GitHub Desktop.

Select an option

Save idettman/5c8eb3fd1551e46ef62354252a1e8810 to your computer and use it in GitHub Desktop.
Get Object Type using Object.toString()
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