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