A while back, I wrote a function about Solid Type Checking. What is funny is that I often am writing just a bit of JavaScript in which I need a better way of checking the type of an object or primitive. Unfortunately, since I have been slacking on the next version of jPaq, I can’t pull the function from there. For this reason, I have written the following JavaScript snippet which defines a typeOf() function in the global namespace:

(function(_, g, u) {
  typeOf = function(o) {
    return o === g
      ? "global"
      : o == u
        ? o === u
          ? "undefined"
          : "null"
        : _.toString.call(o).slice(8, -1);
})({}, this);

This function definition return strings such as the following:

  • Array
  • Date
  • Function
  • global
  • JSON
  • null
  • Number
  • Object
  • RegExp
  • String
  • undefined

The following are some cases that you can use in order to see that the above definition for typeOf() works correctly:

// Test the typeOf function on the specified parameter.
function testOnAll(obj, strObj) {
  alert("typeOf(" + strObj + ") => " + typeOf(obj));

// String
testOnAll("Hello", '"Hello"');

// Array
testOnAll([1,2,"Three",[4,[[5]]]], '[1,2,"Three",[4,[[5]]]]');

// Boolean
testOnAll(false, 'false');

// null
testOnAll(null, 'null');

// undefined
testOnAll(undefined, 'undefined');

// global (use Chrome or last version of function)
testOnAll(window, 'window');

// Function
testOnAll(alert, 'alert');
testOnAll(function(){}, 'function(){}');

// RegExp
testOnAll(/#/, '/#/');

// Date
testOnAll(new Date(), 'new Date()');

// Number
testOnAll(2342, '2342');
testOnAll(3981.3491, '3981.3491');
testOnAll(NaN, 'NaN');
testOnAll(-Infinity, '-Infinity');

// Object
testOnAll({}, '{}');
testOnAll(new Object(), 'new Object()');
testOnAll(new (function(){}), 'new (function(){})');

// Error
testOnAll(new Error("an error"), 'new Error("an error")');
testOnAll(new EvalError("an error"), 'new EvalError("an error")');
testOnAll(new SyntaxError("an error"), 'new SyntaxError("an error")');
testOnAll(new TypeError("an error"), 'new TypeError("an error")');
testOnAll(new RangeError("an error"), 'new RangeError("an error")');
testOnAll(new ReferenceError("an error"), 'new ReferenceError("an error")');
testOnAll(new URIError("an error"), 'new URIError("an error")');

1 Comment

JavaScript – Yet A Better typeOf() Function | Chris West's Blog · September 21, 2012 at 4:42 PM

[…] updated version of Wormbites.  In the process, I wanted to use my typeOf() function that I posted here. The only thing is, I thought it would be even better if the function would optionally take two […]

Leave a Reply

Your email address will not be published. Required fields are marked *