hh05dq
Last Updated: February 25, 2016
·
6.039K
· anthonylevings
Speechrocket4 square

Introspection in JavaScript

<!DOCTYPE html>
<html>
<head><title>JavaScript Introspection</title></head>
<body>
<script>
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>

For more depth see: http://sketchytech.blogspot.co.uk/2013/02/introspection-in-javascript.html

Say Thanks
Respond

2 Responses
Add your response

3866
B4165e8b4f0ddf78233c76e37dd84ab3

Why to not put all types into an object and get type like so for example:

var types = { '[object Array]': 'array' ... };
var x = types[type] || 'not recognized';

Switch is realy needed in rare cases.

over 1 year ago ·
3868
Speechrocket4 square

@shogun I think that's a really good question. The example is part of a tutorial and really intended for the insertion of functions to process the objects depending on type, not just to output the name, as it is doing now.

I like the switch statement for its readability, and the continued readability when functions are inserted, but I'm not a JS expert, and consider myself a forever-learning user, so I am grateful for guidance in these areas.

over 1 year ago ·