JavaScript – Better typeOf() Function

 


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")');

 

One thought on “JavaScript – Better typeOf() Function”

Leave a Reply

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


7 − = two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">