Skip to content

Instantly share code, notes, and snippets.

@tekaratzas
Last active July 24, 2017 13:20
Show Gist options
  • Save tekaratzas/61867ea198f0217308c3baf24549fd58 to your computer and use it in GitHub Desktop.
Save tekaratzas/61867ea198f0217308c3baf24549fd58 to your computer and use it in GitHub Desktop.
Showing the inconsistent behavior and a much better alternative
console.log(typeof "foo" === "string"); //true
console.log(typeof String("foo") === "string"); // true
console.log(typeof new String("foo") === "string"); // false
console.log(typeof 1.2 === "number"); //true
console.log(typeof new Date() === "Date"); //false Date is an Object
console.log(typeof [1,2,3] === "array"); //false, an array is on object!
/** Proper way to test type of object **/
function is(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
console.log(is('String', 'test')); // true
console.log(is('String', new String('test'))); // true
console.log(is('Date', new Date())); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment