JavaScript Type Gotchas
by Jason Aden
JavaScript
// Numbers
console.group("Numbers");
console.log('typeof 37 is number: ', typeof 37 === 'number');
console.log('typeof 3.1415 is number: ', typeof 3.1415 === 'number');
console.log('typeof Math.LN2 is number: ', typeof Math.LN2 === 'number');
console.log('typeof Infinity is number: ', typeof Infinity === 'number');
console.log('typeof NaN is number: ', typeof NaN === 'number'); // even though it's "not a number"
console.log('typeof Number("1") is number: ', typeof Number("1") === 'number'); // useful for typecasting
console.groupEnd();
// Strings
console.group("Strings");
console.log('typeof "" is string: ', typeof "" === 'string'); // empty string is still string
console.log('typeof (typeof 1) is string: ', typeof (typeof 1) === 'string'); // typeof always return a string
console.log('typeof String(Math.PI) is string: ', typeof String(Math.PI) === 'string'); // useful for typecasting
var myString = new String('123');
console.log('myString: ', myString);
console.log('typeof myString is object: ', typeof myString === 'object');
console.log('myString instanceof String: ', myString instanceof String);
console.groupEnd();
// Booleans
console.group("Numbers");
console.log('typeof true is boolean: ', typeof true === 'boolean');
console.log('typeof Boolean(0) is boolean: ', typeof Boolean(0) === 'boolean'); // useful for typecasting
console.groupEnd();
// Arrays
console.group("Arrays");
var myArray = [1,2,3];
console.log('myArray: ', myArray);
console.log('typeof myArray is object: ', typeof myArray === 'object'); // use instanceof Array or Array.isArray()
//console.log('myArray instanceof Array: ', myArray instanceof Array);
console.log('Array.isArray(myArray): ', Array.isArray(myArray));
console.groupEnd();
// Objects
console.group("Objects");
console.log('typeof {a:1} is object: ', typeof {a:1} === 'object');
console.log('typeof new Date() is object: ', typeof new Date() === 'object');
console.groupEnd();
//...