AI solution for Interview Question on BFE.dev
16. How does `instanceOf` work? difference with `typeof`
instanceOf
is an operator in JavaScript that checks if the given object is an instance of a particular class or constructor function. It examines the prototype chain of an object and returns a boolean value.
On the other hand, typeof
is an operator that returns a string indicating the data type of the operand.
The primary difference is that typeof
can only determine primitive data types such as "number", "string", "boolean", "undefined", "null", and "symbol", while instanceOf
can determine whether an object is an instance of a specific constructor function, as well as objects created from custom classes.
A good alternative to typeof
would be using the Object.prototype.toString
method. It returns a string representation of the given object's internal class, such as "[object Object]" for ordinary objects, "[object Array]" for arrays, and "[object Date]" for the Date type.