Question 48

Question

Explain the difference between instanceof and checking for constructor property in JavaScript.

Answer

1. instanceof:

  • Purpose: Checks if an object is an instance of a particular class (or prototype chain). It looks at the object's internal [[Prototype]] chain and verifies if it leads back to the specified constructor function.

  • Syntax: object instanceof Constructor (returns true or false)

  • Advantages:

    • Intuitive: Directly checks for instance relationship.

    • Efficient: Optimized by JavaScript engines.

  • Limitations:

    • Works best with objects created using new.

    • Not reliable for custom classes not built with new.

2. Checking the constructor Property:

  • Purpose: Accesses the constructor function associated with an object.

  • Syntax: object.constructor === Constructor (returns true or false)

  • Advantages:

    • More versatile: Can work with objects created using various methods, including manual assignments.

  • Limitations:

    • Can be misleading if the constructor property has been modified manually (e.g., object tampering).

Example:

function Animal(name) {
  this.name = name;
}

const dog = new Animal("Buddy"); // Created using 'new'

console.log(dog instanceof Animal); // true 
console.log(dog.constructor === Animal); // true 

const cat = {}; 
cat.constructor = Animal;  // Manually set the constructor

console.log(cat instanceof Animal); // false 
console.log(cat.constructor === Animal); // true 

Which to Choose:

  • For objects created with new, use instanceof. It's generally more reliable and efficient.

  • For more flexible checks or when dealing with objects that might not have been created using new, consider checking the constructor property, but be aware of potential manipulation risks.

Last updated