添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Understanding Object Types with JavaScript's instanceof

Hero image for Understanding Object Types with JavaScript's instanceof. Image by Codioful (Formerly Gradienta).
Hero image for 'Understanding Object Types with JavaScript's instanceof.' Image by Codioful (Formerly Gradienta).

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

    : Use typeof for checking primitive types like strings, numbers, or booleans.
  • Complex Objects

    : Use instanceof 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 simple yes / 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 return object 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.

Categories:

  1. Adaptive Development
  2. Cross‑Browser Compatibility
  3. Development
  4. Front‑End Development
  5. Guides
  6. JavaScript
  7. Responsive Development