Skip to content

Instantly share code, notes, and snippets.

@spiralx
Last active February 17, 2017 12:00
Show Gist options
  • Save spiralx/9700972 to your computer and use it in GitHub Desktop.
Save spiralx/9700972 to your computer and use it in GitHub Desktop.
An accurate function for getting the type of a variable in JavaScript, using the fact that Object.prototype.toString() is guaranteed to return an object's internal [[Class]] property when called on it. There's also the isclass() helper function that takes an object and one or more class name strings, and returns True if the class of obj matches …
/**
* classof(obj)
*
* Returns the object's internal [[Class]] property, see
* the other file for example output.
*
* @param {Object?} object
* @return {String}
*/
const classof = v => Object.prototype.toString.call(v).replace(/^\[object\s(.*)\]$/, '$1').toLowerCase();
/**
* isclass(obj, ...types)
*
* Tests whether the class of obj matches any of the types passed in as strings.
*
* @param {Object} obj
* @param {String+} types
* @return {Boolean}
*/
const isclass = (v, ...types) => types.indexOf(classof(v)) !== -1;
/**
* getclasses(obj)
*
* Utility function to help dump the classes of multiple objects
*
* @param {Object*} values
* @return {String}
*/
const getclasses = (...values) => values.map(classof).join(', ');
/* Module exports */
module.exports = { classof, isclass, getclasses };

Examples of the output of classof():

// Standard JS objects

> classof()
'undefined'
> getclasses(undefined, [,][0], window.notDefined)
'undefined'
> classof(null)
'null'
> classof({})
'object'
> classof([])
'array'
> getclasses(function() {}, classof, Object, escape, parseInt)
'function, function, function, function, function'
> (function() { return classof(arguments); })()
'arguments'
> getclasses(new Error, new TypeError, new SyntaxError)
'error, error, error'
> getclasses(true, false)
'boolean, boolean'
> getclasses(4, 1.2, -6, 1.7e666, Infinity, NaN)
'number, number, number, number, number, number'
> classof('')
'string'
> classof(/./)
'regexp'
> classof(new Date)
'date'
> classof(JSON)
'json'
> classof(Math)
'math'

// Browser objects

> classof(window)
'window'
> classof(document)
'document'
> classof(document.body)
'htmlbodyelement'
> getclasses(document.images, document.querySelectorAll('img'))
'htmlcollection, nodelist'
> classof(location)
'location'

// Node.js objects

> classof(global)
'global'
> classof(module)
'object'
> classof(require)
'function'
> classof(process)
'process'

// New objects in ES6 Harmony (using node --harmony)

> classof(function*() { yield 0; })
'function'
> classof(new Set)
'set'
> classof(new Map)
'map'
> classof(new WeakMap)
'weakmap'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment