Skip to content

Instantly share code, notes, and snippets.

@GrahamWalters
Created October 6, 2016 13:04
Show Gist options
  • Save GrahamWalters/e920d75c9e9aea6a39e2a1f41b241912 to your computer and use it in GitHub Desktop.
Save GrahamWalters/e920d75c9e9aea6a39e2a1f41b241912 to your computer and use it in GitHub Desktop.
Get the true type of a variable. Ex: null == "null"
function trueTypeOf (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
console.log(trueTypeOf()); //undefined
console.log(trueTypeOf(null)); //null
console.log(trueTypeOf(NaN)); //number
console.log(trueTypeOf(5)); //number
console.log(trueTypeOf({})); //object
console.log(trueTypeOf([])); //array
console.log(trueTypeOf('')); //string
console.log(trueTypeOf(function () {})); //function
console.log(trueTypeOf(/a/)); //regexp
console.log(trueTypeOf(new Date())) //date
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment