Created
April 20, 2016 16:32
-
-
Save rcanepa/333769d7a9c5293299b1525964b7e1a2 to your computer and use it in GitHub Desktop.
Javascript type checking
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
// 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