- read

How to Natively Implement instanceOf in JavaScript

Xiuer Old 52

Photo by Nagara Oyodo on Unsplash


The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

Interviewer: to write a fakeInstanceOf, you must meet the following test cases:

function fakeInstanceOf (instance, parent): Boolean {}

//=> true
fakeInstanceOf([], Array)

//=> true
fakeInstanceOf([], Object)

//=> true
fakeInstanceOf(x => x, Object)

//=> false
fakeInstanceOf('hello', Object)

The following is a reference

function fakeInstanceOf (instance, parent) {
if (typeof(instance) !== 'object' && typeof(instance) !== 'function') {
return false
let proto = instance?.__proto__ || null
while (true) {
if (proto === null) { return false }
if (proto === parent.prototype) { return true }
proto = proto.__proto__