Summary of the differences between typeof and instanceof in JS

  • 2020-03-29 23:44:24
  • OfStack

Typeof and instanceof are commonly used in JavaScript to determine whether a variable is null or of what type. But there are differences:

typeof

Typeof is a unary operation that comes before an operand that can be of any type.

The return value is a string that specifies the type of operand. Typeof generally returns only the following results:

Number, Boolean, string, the function, object, undefined. We can use typeof to get whether a variable exists, such as if(typeof a! ="undefined"){alert("ok")}, instead of using if(a), because if a does not exist (undeclared), an error will occur. For special objects such as Array,Null, etc., typeof will always return object, which is the limitation of typeof.

instanceof

-sheldon: no, no, no

A instanceof b? Alert (" true ") : alert (" false "); //a is an instance of b? True, false

Instanceof is used to determine whether a variable is an instanceof an object, such as var a=new Array(); Alert (a instanceof Array);
The alert(an instanceof Object) returns true; This is because Array is an object
The subclass. Function test(){}; Var a = new test (); Alert (an instanceof test) returns

One more thing to say about instanceof is that arguments to function, which we might all agree is one
Array, but if you test it with instaceof, you'll see that arguments is not an Array object, although it looks similar.

In addition:

Test var a=new Array(); If (an instanceof Object) alert('Y'); The else alert (" N ");

Have to 'Y'

But if (window instanceof Object) alert('Y'); The else alert (" N ");

Have to 'N'

Therefore, the object of instanceof test here refers to the object in js syntax, not to the dom model object.

Using typeof makes some difference

Alert (typeof (Windows)) will have to object


Related articles: