Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Created April 20, 2016 16:32
Show Gist options
  • Save rcanepa/333769d7a9c5293299b1525964b7e1a2 to your computer and use it in GitHub Desktop.
Save rcanepa/333769d7a9c5293299b1525964b7e1a2 to your computer and use it in GitHub Desktop.
Javascript type checking
// Checking types
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]
// Helper function
var getType = function (elem) {
return Object.prototype.toString.call(elem);
};
// An example
if (getType(person) === '[object Object]') {
person.getName();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment