
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 constructor
-
object
: 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); //=> true
In 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 swim
Here, 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); //=> true
When to use
instanceof
vs
typeof
-
Primitive Types
: Usetypeof
for checking primitive types like strings, numbers, or booleans. -
Complex Objects
: Useinstanceof
when 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
:instanceof
considers the prototype chain, making it more versatile for checking an object's inheritance.
Wrapping up
-
Use
instanceof
if you want a simpleyes
/no
answer to the question "Is this variable an instance of xyz?". -
Use
typeof
if you want an answer to the question "What type is my variable? -
Understand that
typeof
might returnobject
when 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.
More articles
-
Understanding Transient Props in styled‑components. Understanding Transient Props in
-
Creating Custom Viewport Units Instead of Using vh and vw. Creating Custom Viewport Units Instead of Using
vh
andvw
-
Check If a String Contains Only Whitespace with JavaScript. Check If a String Contains Only Whitespace with JavaScript
-
Optimising gatsby‑image Even Further. Optimising
gatsby‑image
Even Further -
Toggle a Boolean in JavaScript. Toggle a Boolean in JavaScript
-
LeetCode: Converting Roman Numerals to Integers. LeetCode: Converting Roman Numerals to Integers
-
Commenting in Front‑End Languages. Commenting in Front‑End Languages
-
Understanding and Solving LeetCode's 'Add Two Numbers' Problem. Understanding and Solving LeetCode's 'Add Two Numbers' Problem
-
Detecting Breakpoints in React Using Chakra UI. Detecting Breakpoints in React Using Chakra UI
-
Disabling Source Maps in Gatsby for Production. Disabling Source Maps in Gatsby for Production
-
Horizontal & Vertical Scanning: The Longest Common Prefix Problem. Horizontal & Vertical Scanning: The Longest Common Prefix Problem
-
Has Google Killed AMP? Has Google Killed AMP ?