Typeof is used to obtain the type of a variable. Typeof generally can only return the following results: number, boolean, string, function, object, undefined. We can use typeof to get whether a variable exists, such as
if(typeof a != "undefined"){} instead of using if(a) because if a does not exist (undeclared) it will An error occurs. Using typeof for special objects such as Array and Null will always return object. This is the limitation of typeof.
If we want to get whether an object is an array, or determine whether a variable is an instance of an object, we have to use instanceof. instanceof is used to determine whether a variable is an instance of an object. For example, var a=new Array(); alert(a instanceof Array); will return true, and alert(a instanceof Object) will also return true; this is because Array is subclass of object. Another example: function test(){};var a=new test();alert(a instanceof test) will return true.
When it comes to instanceof, we have to insert one more problem, which is the arguments of function. We may all think that arguments are an Array, but if you use instanceof to test, you will find that arguments are not an Array object, even though it looks very similar. .
The instanceof operator in JavaScript returns a Boolean value, indicating whether the object is an instance of a specific class.
Usage:
result = object instanceof class
where result is a required option. Any variable.
object is required. Any object expression.
class is required. Any defined object class.
Explanation
If object is an instance of class, the instanceof operator returns true. Returns false if object is not an instance of the specified class, or if object is null.
Instanceof operator in JavaScript
The following example illustrates the usage of instanceof operator.