I saw a job posting that illustrated the JavaScript/ECMAScript knowledge-level the candidate needed with:
can you figure out whether you’re working with an array or arguments list without the use of 3rd party code?
I was intrigued, because I didn’t know the answer.
Two ways (of many, I’m sure) to determine the type of JavaScript Object you’re working with is by
using instaceof or Object.prototype.toString
instaceof
Instaceof will give you a boolean response. It’s useful to determine if you’re working with a specific kind of object.
1 2 3 4 5 6 7 | |
Instanceof evaluates to true if the object inherits from the class’s prototype:
1 2 | |
This evaluates to true since p inherits from Person.prototype. It’s worth noting that
using the new keyword is imperative.
Arguments is not a valid instanceof object, so we can only use this to tell if we’re
dealing with an Array or something else.
Object.prototype.toString
Calling this returns the type of object
1 2 3 4 5 6 7 | |
You could then use indexOf or search to check for ‘Arguments’ or ‘Array’.
Without a doubt, there are other ways to do this in JavaScript. That’s what makes it fun—you’re never done learning.