Created
October 3, 2013 08:10
-
-
Save dannycallaghan/6806758 to your computer and use it in GitHub Desktop.
(Better) JavaScript Type Detection
This file contains 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
/* Better type detection */ | |
/* | |
- Checking a supposed array for a method like slice() isn't robust enough, as there's no reason why a non-array couldn't have a method of the same name | |
- instanceof Array works incorrectly when used across frames in some IE versions | |
*/ | |
// ARRAY | |
var alpha = []; | |
console.log( typeof alpha ); // "object" | |
console.log( alpha.constructor === Array ); // true | |
console.log( Object.prototype.toString.call( alpha ) ); // "[object Array]" | |
console.log( Array.isArray( alpha ) ); // true (ECMAScript 5 only) | |
// OBJECT | |
var bravo = {}; | |
console.log( bravo.constructor === Object ); // true | |
console.log( Object.prototype.toString.call( bravo ) ); // "[object Object]" | |
// STRING | |
var charlie = "Hello"; | |
console.log( charlie.constructor === String ); // true | |
console.log( Object.prototype.toString.call( charlie ) ); // "[object String]" | |
// NUMBER | |
var delta = 1; | |
console.log( delta.constructor === Number ); // true | |
console.log( Object.prototype.toString.call( delta ) ); // "[object Number]" | |
// BOOLEAN | |
var echo = false; | |
console.log( echo.constructor === Boolean ); // true | |
console.log( Object.prototype.toString.call( echo ) ); // "[object Boolean]" | |
// REGULAR EXPRESSION | |
var foxtrot = /foo/gmi; | |
console.log( foxtrot.constructor === RegExp ); // true | |
console.log( Object.prototype.toString.call( foxtrot ) ); // "[object RegExp]" | |
// NULL | |
var golf = null; | |
console.log( golf.constructor ); // Cannot read property 'constructor' of undefined | |
console.log( Object.prototype.toString.call( golf ) ); // "[object Null]" | |
// UNDEFINED | |
var hotel; | |
console.log( hotel.constructor ); // Cannot read property 'constructor' of undefined | |
console.log( Object.prototype.toString.call( hotel ) ); // "[object Undefined]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment