

Ask HN: (JavaScript): How often have you needed instanceOf and/or isProtoTypeOf? - nni

I&#x27;m not questioning the utility of these, I&#x27;m just curious how often in day-to-day practice folks end up needing them.
======
marcofiset
Most of the time, I consider the use of instanceof as a code smell. You could
easily replace the type checking with a polymorphic method call. For example,
say you're doing:

if (obj instanceof Foo) obj.doSomething(); else if (obj instanceof Bar)
obj.doSomethingElse();

In that case, if it makes sense for Foo and Bar to share a common ancestor,
the ideal thing would be to have a doSomething function on the parent class
(or parent prototype in javascript), which is overridden in both Foo and Bar,
therefore making the type checking unnecessary. Simply call doSomething on the
object.

You should note that this is not applicable to every situation, but it should
take care of most cases where you would need to use instanceof.

------
coreyp_1
I would think that it depends on how structured your code needs to be. For
example, I'm working on a soon-to-be open source project which makes heavy use
of prototypical inheritance, so I use it a lot. That being said, for one-off
projects that do not require a lot of extensibility, you might not use it at
all.

------
Spoom
I've only ever used it to check if a given variable contains an Array. Seems
to be the easiest way.

