Home >Web Front-end >JS Tutorial >The difference between typeof and instanceof in js

The difference between typeof and instanceof in js

下次还敢
下次还敢Original
2024-05-07 18:48:18451browse

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 js

##The difference between typeof and instanceof in JavaScript

JavaScript

typeof and instanceof are both methods used to check variable types, but they have different purposes and behaviors.

typeof

    Returns a string representing the original type of the variable.
  • Can be used to check primitive types (such as strings, numbers, and Boolean values) and reference types (such as objects, arrays, and functions).
  • Syntax: typeof variable

##instanceof

Returns a Boolean value indicating whether the variable belongs to the given constructor.
  • Syntax:
  • variable instanceof constructor
  • ##Main difference

Features Return value StringBoolean valueCheck typePrimitive and reference typeReference type BehaviorReturn the original type of the variableCheck whether the variable belongs to an instance of the specified constructorExample
typeof instanceof

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn