Instanceof operator in JavaScript

JavascriptFront End TechnologyObject Oriented Programming

The instance of operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In a simpler languange, it tests if a variable is of a certain type. But it has a few caveats. Let us look at some examples.

Primitives

Strings and numbers are primitive values, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in regular objects.

Example

console.log(1 instanceof Number)
console.log(new Number(1) instanceof Number)
console.log("" instanceof String)
console.log(new String("") instanceof String)

Output

false
true
false
true

Constructible functions

Functions that return their objects(JS Classes) can have their objects checked using the instanceof operator.

Example

function Person(name) {
   this.name = name
}
let john = new Person("John");
console.log(john instanceof Person)

Output

true

Inheritence

JS supports prototypical inheritence, so if you check for instanceof for any class in the hierarchy, it'll return true.

Example

class Person {}
class Student extends Person {
   constructor(name) {
      super()
      this.name = name
   }
}
let john = new Student("John");
console.log(john instanceof Person)
console.log(john instanceof Student)

Output

true
true
raja
Published on 16-Sep-2019 08:09:05
Advertisements