Objects versus Primitives
For example using
'someString'.trim(); will spin up an Object underneath and call the
.trim() method on it.
undefined are weird (both Primitives too), and distinguish between no value or an unknown value (
null is unknown value,
undefined is totally not known or even declared). There is also an Error object.
Object’s however are a different story. You’ll notice I’ve not mentioned
RegExp, these are types of Object, let’s investigate. Under the
Object tree we have:
From MDN: “The
typeof operator returns a string indicating the type of the unevaluated operand”.
Based on our newly acquired knowledge from the above, you wouldn’t expect this to happen:
Function is an Object, but tells us it’s a
Array is an Object and says it is.
null is an Object, and so is our
RegExp. What happened?
typeof operator is a bit strange. Unless you know how to really use it, simply avoid it to avoid headaches. We wouldn’t want something like this to happen:
typeof let us down here, what we really wanted to know was that
person was a plain Object.
True Object types
There’s a really simple way, though to look at it looks like a hack:
.toString() method is accessed using
Object.prototype because every object descending from
Object prototypically inherits it. By default, we get
[object Object] when calling
We can use
.call() to change the
this context (as it converts its argument to a value of type) and, for example, if we use
.call(/test/i) (a Regular Expression) then
[object Object] becomes
Which means if we run our test again using all JS types:
We can then push this into a function and more reliably validate our previous function:
To keep things DRY and save writing
=== '[object Object]' or whatever out each time, we can create methods to simply reference. I’ve used
.slice(8, -1); inside the
getType function to remove the unnecessary
] parts of the String:
I put together all the above methods into a micro-library called Axis.js which you can use:
The code powering that does some cool stuff for those interested: