Home >Web Front-end >JS Tutorial >Detailed explanation of the difference between instanceof and typeof operators_jquery
1. instanceof operator:
This operator can determine whether a variable is an instance of an object (class), and the return value is of Boolean type.
To understand its function, you must have some understanding of object orientation:
The code example is as follows:
The above code will output true because str is an object instance of the object String.
Generally speaking, only objects created using the constructor will return true, otherwise false will be returned. However, arrays are an exception and will return true.
2. typeof operator:
This operator can return a string to describe the type of metaarithmetic. Its return value has the following possibilities:
Let’s look at a code example:
In the above code, the first one can output the exact type "string", but the second one is indeed "object", which is not accurate.
Generally speaking, if the operation using typeof is in the form of a direct quantity, it can return accurate results. If it is an object created using a constructor, "object" will be returned. However, there is an exception for arrays, whether it is a direct quantity or not. Return "object".