This AI is still in early stages of development.

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 15 Next »

An alternative to Javascript's "typeof" that provides more consistent results...

 

Syntax

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

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

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

Examples

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

// 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...

Availability

This feature requires:

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

See also

Related articles:

 

Javascript's typeof operator
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"
typeOf(stuff)
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"
  • No labels