Last Updated: June 29, 2023
·
9.328K
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside