Introspection in JavaScript

Introspection is an important tool, especially for code interfacing with modern APIs over the Internet. It is a way of ensuring that the type (or class) of object can be processed in the appropriate way. For a tutorial on how to determine the class of an object, see this tutorial on Adobe's developer connection blog, which examines the instanceof operator.

This post will examine a slightly different type of introspection, looking at the basic type of object that is received, for example a string, number, array, or object. This is performed using this call:

Object.prototype.toString.call();

So first we're going to create a range of different of object types:

var num = 9;
var array = [];
var obj = {"key":"value"};
var string ="string";

Next we're going to create a switch statement to process the object types, which will begin with a global variable (that's the var x bit) to store the response:

var x;

function introspect(object)
{

var type = Object.prototype.toString.call(object);

switch(type){
case '[object Array]':
x = "array";
break;

case '[object Object]':
x = "object";
break;

case '[object String]':
x = "string";
break;

case '[object Number]':
x = "number";
break;

default:
x ="not recognized";
}}

All we have to do now is to send one of our objects to the function and write out the reply:

introspect(string);
document.write(x);

Experiment with changing the object/variable and change the code to send strings and numbers to the function that are not stored as variables, e.g. "test", 7, {} or ["one","two","three"].

Finally, here's the entire copy and paste code (with a few more object types added in)

<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
var num = 9;
var array = [];
var obj = {"key":"value"};
var string ="string";

var x;

function introspect(object)
{

var type = Object.prototype.toString.call(object);

switch(type){
case '[object Array]':
x = "array";
break;

case '[object Object]':
x = "object";
break;

case '[object String]':
x = "string";
break;

case '[object Number]':
x = "number";
break;

case '[object Boolean]':
x= "boolean";
break;

case '[object Date]':
x= "date";
break;

case '[object Undefined]':
x= "undefined";
break;

case '[object Null]':
x= "null";
break;

default:
x ="not recognized";
}}

introspect(["one","two","three"]);
document.write(x);
</script></body>
</html>

In real world use once you know the type of object you are dealing with you can send it off to another function to be processed in the appropriate way, and even bat arrays and objects back and forth between functions such as this until all strings and numbers are extracted.

Further reading

Higher-Order, JavaScript parasitic inheritance, power constructors and instanceof
JavaScript Garden, Types
Keith Peters, Object types in JavaScript
StackOverflow, 'The most accurate way to check JS object type?'


Comments