Sobes.tech
Junior

What does the instanceof operator check in JavaScript?

sobes.tech AI

Answer from AI

The instanceof operator in JavaScript checks whether an object is an instance of a specific class or constructor.

How it works:

  1. The instanceof operator checks for the presence of the constructor's prototype in the object's prototype chain.
  2. If the constructor's prototype is found in the chain, the result is true.
  3. Otherwise, the result is false.

Examples:

// Creating a class
class Animal {
  // Constructor
  constructor(name) {
    this.name = name;
  }
}

// Creating an instance of the class
let dog = new Animal("Buddy");

// Checking if dog is an instance of Animal
console.log(dog instanceof Animal); // true

// Checking if dog is an instance of Object (it is, through the prototype chain)
console.log(dog instanceof Object); // true

// Checking if dog is an instance of Array (it is not)
console.log(dog instanceof Array); // false

// Checking with built-in types
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true

let num = 123;
console.log(num instanceof Number); // false (primitives behave specifically with instanceof)
// For primitives created with new
let numObj = new Number(123);
console.log(numObj instanceof Number); // true

Features:

  • instanceof works through the prototype chain, so it can return true for parent constructors.
  • For primitive types (string, number, boolean, null, undefined, symbol, bigint), instanceof usually returns false unless they are created via their object wrappers (new String(), new Number(), etc.).
  • It can be unreliable across different JavaScript execution contexts (e.g., different browser windows or iframes), as each context has its own constructors.

Alternative type checks:

  • typeof: Returns a string indicating the basic data type (string, number, boolean, object, function, undefined, symbol, bigint). Not suitable for checking class membership.
  • Object.prototype.toString.call(): Returns a more precise string with the object type ("[object Array]", "[object Date]", etc.).

Overall, instanceof is useful for checking whether an object belongs to a specific class or its ancestors in the inheritance hierarchy.

What does the instanceof operator check in… - sobes.tech