Web Front-end
JS Tutorial
Type checking in JavaScript: the difference between typeof and instanceof operatorsType checking in JavaScript: the difference between typeof and instanceof operators
In JavaScript both typeof and instanceof operators can perform type checking, so what are the differences between them? This article will introduce to you the difference between typeof and instanceof operators. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Related recommendations: "javascript video tutorial"
Smarties must know that JS is a weakly typed language, and variables are There are no restrictions on the type.
For example, if we create a variable using the string type, we can later assign a number to the same variable:
let message = 'Hello'; // 分配一个字符串 message = 14; // 分配一个数字
This dynamic gives us flexibility and simplifies variables statement.
On the downside, we can never be sure that a variable contains a value of a certain type. For example, the following function greet(who) requires a string parameter, however, we can call the function with any type of parameter:
function greet(who) {
return `Hello, ${who}!`
}
greet('World'); // => 'Hello, World!'
// You can use any type as argument
greet(true); // => 'Hello, true!'
greet([1]); // => 'Hello, 1!'
Sometimes we need to check the value of a variable in JS Type, what to do?
Use the typeof operator and instanceof to check the instance type.
1.<span style="font-size: 18px;">typeof</span>operator
in JS , the basic types include String, Number, Boolean, and Symbol, etc. In addition, there are functions, objects, and the special values undefined and null.
typeof is the operator used to determine the type of expression:
const typeAsString = typeof expression;
expression evaluates to what we want to find value of type. expression can be a variable myVariable, a property accessor myObject.myProp, a function call myFunction() or a number 14.
typeof expression, depending on the value of expression, the result may be: 'string', 'number' , 'boolean', 'symbol', 'undefined', 'object', 'function' .
Let’s take a look at each type of typeof operator:
A) String:
const message = 'hello!'; typeof message; // => 'string'
B) Number:
const number = 5; typeof number; // => 'number' typeof NaN; // => 'number'
C) Boolean:
const ok = true; typeof ok; // => 'boolean'
D) Symbol:
const symbol = Symbol('key');
typeof symbol; // => 'symbol'
E) undefined:
const nothing = undefined; typeof nothing; // => 'undefined'
F) Objects:
const object = { name: 'Batman' };
typeof object; // => 'object'
const array = [1, 4, 5];
typeof array; // => 'object'
const regExp = /Hi/;
typeof regExp; // => 'object'
G) Functions :
function greet(who) {
return `Hello, ${who}!`
}
typeof greet; // => 'function'
1.1 typeof null
As we can see above, the result of using typeof to determine the object is 'object' .
However, typeof null will also be calculated as 'object'!
const missingObject = null; typeof missingObject; // => 'object'
typeof null is 'object' is a bug in the initial implementation of JS.
Therefore, when using typeof to detect objects, you need to additionally check null:
function isObject(object) {
return typeof object === 'object' && object !== null;
}
isObject({ name: 'Batman' }); // => true
isObject(15); // => false
isObject(null); // => false
1.2 typeof and undefined variables
Although typeof expression is usually determined by the type of expression, you can also use typeof to determine whether a variable is defined.
// notDefinedVar is not defined notDefinedVar; // throws ReferenceError
typeof has a nice property that when typeof evaluates the type of an undefined variable, the ReferenceError error is not raised:
// notDefinedVar is not defined typeof notDefinedVar; // => 'undefined'
VariablenotDefinedVar is not defined in the current scope. However, typeof notDefinedVar does not throw a reference error and instead evaluates to 'undefined'.
We can use typeof to detect whether a variable is undefined. If typeof myVar === 'undefined' is true, then myVar is not defined.
2. instanceof operator
The usual way to use a JS function is to call it by adding a pair of brackets after its name:
function greet(who) {
return `Hello, ${who}!`;
}
greet('World'); // => 'Hello, World!'
greet('World') is a regular function call.
JS functions can do much more: they can even construct objects! To have a function construct an object, just use the new keyword before the regular function call:
function Greeter(who) {
this.message = `Hello, ${who}!`;
}
const worldGreeter = new Greeter('World');
worldGreeter.message; // => 'Hello, World!'
new Greeter('World') is to create the instance Constructor call of worldGreeter.
How to check if JS created a specific instance using a specific constructor? Use the instanceof operator:
const bool = object instanceof Constructor;
where object is the expression that evaluates the object, and Constructor is the class or function that constructs the object , instanceof evaluates to a Boolean value.
worldGreeter The instance is created using the Greeter constructor, so this worldGreeter instanceof Greeter evaluates to true.
Starting from ES6, you can use class to define objects. For example, define a class Pet and then create an instance of it myPet:
class Pet {
constructor(name) {
this.name = name;
}
}
const myPet = new Pet('Lily');
new Pet('Lily')是创建实例myPet的构造调用。
由于myPet是使用Pet类构造的-const myPet = new Pet('Lily'), 所以 myPet instanceof Pet 的结果为 true:
myPet instanceof Pet; // => true
但是,普通对象不是Pet的实例:
const plainPet = { name: 'Zoe' };
plainPet instanceof Pet; // => false
我们发现instanceof对于确定内置的特殊实例(如正则表达式、数组)很有用:
function isRegExp(value) {
return value instanceof RegExp;
}
isRegExp(/Hello/); // => true
isRegExp('Hello'); // => false
function isArray(value) {
return value instanceof Array;
}
isArray([1, 2, 3]); // => true
isArray({ prop: 'Val' }); // => false
2.1 instanceof 和父类
现在,Cat 扩展了父类Pet:
class Cat extends Pet {
constructor(name, color) {
super(name);
this.color = color;
}
}
const myCat = new Cat('Callie', 'red');
不出所料,myCat是Cat类的实例:
myCat instanceof Pet; // => true
但同时,myCat也是基类Pet的一个实例:
myCat instanceof Pet; // => true
3. 总结
JS 是一种弱类型的语言,这意味着对变量的类型没有限制。
typeof expression可以用来查看 expression 的类型,结果是可能是其中的一个:'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'。
typeof null的值为'object',因此使用typeof检测对象的正确方法是typeof object ==='object'&& object!== null。
instanceof运算符让我们确定实例的构造函数。 如果object是Constructor的实例,则object instanceof Constructor为true。
原文地址:https://dmitripavlutin.com/javascript-typeof-instanceof/
作者:Dmitri Pavlutin
译文地址:https://segmentfault.com/a/1190000038312457
更多编程相关知识,请访问:编程课程!!
The above is the detailed content of Type checking in JavaScript: the difference between typeof and instanceof operators. For more information, please follow other related articles on the PHP Chinese website!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.





