
Understanding Object Types with JavaScript's instanceof

In JavaScript, determining the type of an object or variable is a common task, and two operators often come into play: typeof (which I've written about in detail before) and instanceof. Whilst typeof is useful for more primitive types, instanceof shines when working specifically with object instances.
In this article, I intend to explore instanceof, how it compares to its typeof sibling, and talk through some scenarios where each is best‑suited.
What is instanceof?
Starting with the basics instanceof is a binary operator used in JavaScript to check whether an object is an instance of a particular class or constructor function. It helps in determining the specific prototype chain of an object.
Syntax
object instanceof constructorobject: The object we want to test.constructor: The constructor function we want to check the object against.
Pretty simple, right?
Using instanceof in JavaScript
Here's a relatively basic example to start with:
function Car(make, model) { this.make = make; this.model = model;}const myCar = new Car('Tesla', 'Model Y');console.log(myCar instanceof Car); //=> trueIn this example, myCar is an instance of the Car constructor, so myCar instanceof Car returns true. It probably seems really obvious when put into code like that...!
instanceof in TypeScript
Now, we all know that TypeScript seems to do a lot of this checking for us beforehand. We define interfaces and types for our variables, and can then be confident that they are the 'type of', or 'instance of' the type expected.
Nevertheless, instanceof (and typeof) is still relevant in TypeScript, especially for runtime type checks. TypeScript's type system operates at compile time, and there are scenarios where you might need to ascertain an object's type at runtime. For example where a prop passed into your function could conceivably be one type.
This also surfaces when it comes to class type guards, where you can use TypeScript, with instanceof, to narrow down the (custom) type of an object within a conditional block.
For example:
class Bird { fly() { console.log('I can fly'); }}class Fish { swim() { console.log('I can swim'); }}const move = (animal: Bird | Fish): void => { if (animal instanceof Bird) { animal.fly(); } else { animal.swim(); }};const bird = new Bird();const fish = new Fish();move(bird); // Output: I can flymove(fish); // Output: I can swimHere, I'm using instanceof to differentiate between Bird and Fish instances, and react accordingly.
Comparing instanceof and typeof
Inevitably, there is some overlap between the two, but whist both instanceof and typeof are used for type checking, they serve quite different purposes.
typeof
typeof is a unary operator that returns a string indicating the type of the operand. typeof is useful for primitive types like 'string', 'number', 'boolean', or 'undefined'.
console.log(typeof 'Hello'); //=> 'string'console.log(typeof 42); //=> 'number'instanceof
instanceof checks the prototype chain of an object against a constructor function to see if it matches. It is more suitable for checking complex object types created through constructor functions or classes, and only returns true or false.
class SpaceShuttle {}const discovery = new SpaceShuttle();console.log(discovery instanceof SpaceShuttle); //=> trueWhen to use instanceof vs. typeof
Primitive Types
: Usetypeoffor checking primitive types like strings, numbers, or booleans.Complex Objects
: Useinstanceofwhen dealing with complex objects, especially when you need to check if an object is an instance of a custom particular class or constructor function.Limitations of
typeof: Since typeof can return 'object' for various non‑primitive types (like arrays and null), it iss not reliable for detailed type checking of objects.Prototype Chain Checking
:instanceofconsiders the prototype chain, making it more versatile for checking an object's inheritance.
Wrapping up
- Use
instanceofif you want a simpleyes/noanswer to the question "Is this variable an instance of xyz?". - Use
typeofif you want an answer to the question "What type is my variable? - Understand that
typeofmight returnobjectwhen it really means something altogether different.
Clear as mud.
So: understanding the differences between typeof and instanceof is important in JavaScript development for accurate type checking. Whilst typeof is suitable for simple, primitive types, instanceof provides a more nuanced approach for complex objects and their prototype chains. Knowing when to use each can greatly enhance the robustness and reliability of your JavaScript code.
Related Articles

Implementing Authentication in Next.js Using NextAuth.js. 
The Difference Between == and === in JavaScript. The Difference Between
==and===in JavaScript
The Difference Between JavaScript Callbacks and Promises. The Difference Between JavaScript Callbacks and Promises

Optional Chaining in JavaScript (?.). Optional Chaining in JavaScript (
?.)
Implementing a Trie in TypeScript: Solving 'Implement Trie (Prefix Tree)'. Implementing a Trie in TypeScript: Solving 'Implement Trie (Prefix Tree)'

Dynamic Routes in Next.js. Dynamic Routes in Next.js

React's Virtual DOM vs. the Real DOM. React's Virtual DOM vs. the Real DOM

Using the CSS :has Pseudo‑Class. Using the CSS
:hasPseudo‑Class
Binary Search on the Answer: Solving 'Koko Eating Bananas'. Binary Search on the Answer: Solving 'Koko Eating Bananas'

Angular Standalone Components: Do We Still Need Modules? Angular Standalone Components: Do We Still Need Modules?

Adding Static Files to a Gatsby Site. Adding Static Files to a Gatsby Site

Find Peak Element: Binary Search Without a Fully Sorted Array. Find Peak Element: Binary Search Without a Fully Sorted Array