Home >Web Front-end >JS Tutorial >The difference between typeof and instanceof in js
The difference between typeof and instanceof in JavaScript: typeof returns a string representing the original type of the variable. instanceof returns a Boolean value indicating whether the variable belongs to the given constructor. typeof checks primitive and reference types, while instanceof only checks reference types. typeof returns the original type of the variable, while instanceof checks whether the variable belongs to an instance of the specified constructor.
##The difference between typeof and
instanceof in JavaScript
typeof and
instanceof are both methods used to check variable types, but they have different purposes and behaviors.
typeof
##instanceof
typeof |
instanceof |
|
---|---|---|
Boolean value | Check type | |
Reference type | Behavior | |
Check whether the variable belongs to an instance of the specified constructor |
<code class="javascript">// 原始类型 console.log(typeof "Hello"); // "string" console.log(typeof 123); // "number" console.log(typeof true); // "boolean" // 引用类型 console.log(typeof [1, 2, 3]); // "object" (实际类型为数组) console.log(typeof { name: "John Doe" }); // "object" (实际类型为对象) // instanceof let person = { name: "John Doe" }; console.log(person instanceof Object); // true</code>Summary
typeof
is used to check the original type of a variable, while instanceof is used to check if a variable belongs to a given constructor. Although they both can check variable types, they serve different purposes and return different types of values.
The above is the detailed content of The difference between typeof and instanceof in js. For more information, please follow other related articles on the PHP Chinese website!