Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Excerpt

An alternative to Javascript's "typeof" that provides more consistent resultsReturns the name of the constructor used to create an object...

 

Syntax

typeOf() can be used as a global function, or as a method of any object...

Code Block
themeRDark
languagejavascript
linenumberstrue
var returnValue = typeOf(obj);
// or...
var returnValue = obj.typeOf();

Parameters

Parameter / ObjectTypeMandatoryDescriptionUtil.js version
objVariant(error)

By default, typeOf() will return the type of 'this' – the object that it is a method of.

If you pass in an object of any kind as a parameter, typeOf() will return the name of that object's constructor.

1.0

Return

valye

value

Returns the string name of the constructor of the class from which the object was derived (or primitive value type coerced to)instantiated.

Examples

Car must be taken when checking the type of primitive values...

Code Block
themeRDark
languagejavascript
linenumberstrue
// don't do this:
var returnValue = 5.typeOf(); // Syntax Error

// instead, do this:
var returnValue = typeOf(5); // "number"
var returnValue = (5).typeOf(); // "number"
 
// Or if you want a l33t way of doing it:
var returnValue = 5..typeOf(); // "number" (:

The following examples show the key differences between Javascript's typeof operator and the typeOf() function...

Div
classbox

Availability

This feature requires:

  • Util.js v0.3 and above.
  • Can be accessed via global object/scope.
Div
classbox

See also

Related articles:

 

Section
Column
width47%
Code Block
themeRDark
languagejavascript
titleJavascript's typeof operator
linenumberstrue
typeof {a: 4}; //"object"
typeof [1, 2, 3]; //"object"
(function() {return typeof arguments})(); //"object"
typeof new ReferenceError; //"object"
typeof new Date; //"object"
typeof /a-z/; //"object"
typeof Math; //"object"
typeof JSON; //"object"
typeof new Number(4); //"object"
typeof new String("abc"); //"object"
typeof new Boolean(true); //"object"
Column
width53%
Code Block
themeRDark
languagejavascript
titletypeOf(stuff)
linenumberstrue
typeOf({a: 4}); //"object"
typeOf([1, 2, 3]); //"array"
(function() {return typeOf(arguments)})(); //"arguments"
typeOf(new ReferenceError); //"error"
typeOf(new Date); //"date"
typeOf(/a-z/); //"regexp"
typeOf(Math); //"math"
typeOf(JSON); //"json"
typeOf(new Number(4)); //"number"
typeOf(new String("abc")); //"string"
typeOf(new Boolean(true)); //"boolean"