Problem Statement
What does the instanceof operator check?
Explanation
The instanceof operator checks if an object's prototype chain includes a constructor's prototype property.
It returns true if the constructor's prototype appears anywhere in the object's prototype chain.
Instanceof does not check if the object was directly created by that constructor, only if the prototype exists in the chain.
It returns false for primitive values.
Instanceof is useful for type checking and validation in JavaScript.
You can manipulate prototypes to trick instanceof, so it is not completely reliable.
Code Solution
SolutionRead Only
function Person(name) {
this.name = name;
}
function Animal(type) {
this.type = type;
}
const john = new Person('John');
const dog = new Animal('Dog');
// Basic instanceof
console.log(john instanceof Person); // true
console.log(dog instanceof Animal); // true
console.log(john instanceof Animal); // false
// Everything is an instance of Object
console.log(john instanceof Object); // true
console.log(dog instanceof Object); // true
console.log([] instanceof Object); // true
// Arrays
const arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
// Primitives return false
console.log(5 instanceof Number); // false
console.log('hello' instanceof String); // false
console.log(true instanceof Boolean); // false
// Wrapper objects return true
console.log(new Number(5) instanceof Number); // true
// How instanceof works
function myInstanceof(obj, constructor) {
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === constructor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
console.log(myInstanceof(john, Person)); // true
console.log(myInstanceof(john, Object)); // true
// Can be tricked by changing prototype
const obj = {};
console.log(obj instanceof Array); // false
Object.setPrototypeOf(obj, Array.prototype);
console.log(obj instanceof Array); // true (tricked!)