Last Updated: June 29, 2023
·
8.408K
· anthonylevings

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

1 Response
Add your response

@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 ·