惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Type checking in JavaScript: typeof and instanceof operators
Dmitri Pavlutin · 2020-11-24 · via Dmitri Pavlutin Blog

JavaScript is a loosely-typed language, so there is no restriction on the variable's type.

For example, if you've created a variable with a string type, later you can assign to the same variable a number:


let message = 'Hello'; // assign a string

message = 14; // assign a number


Such dynamism gives you flexibility and simplifies variables declaration.

On the other side, you can never be sure that a variable contains a value of a certain type. For example, the following function greet(who) expects a string argument, however, you can invoke the function with any type of argument:


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


That's why, sometimes, you need to check the variable's type in JavaScript — using typeof operator, as well as instanceof to check instance types.

Let's see in more detail how to use typeof and instanceof operators in JavaScript.

1. typeof operator

In JavaScript, you can find primitive types like strings, numbers, booleans, symbols. Additionally, there are functions, objects, and the special values undefined and null.

typeof is the operator that let's you determine the type of the expression:


const typeAsString = typeof expression;


where expression evaluates to a value which type you'd like to find. expression can be a variable myVariable, property accessor myObject.myProp, function invocation myFunction(), or even a raw literal 14.

typeof expression, depending on the value of expression, evaluates to one of the strings: 'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'.

Let's see how typeof operator works for each type:

A) Strings:


const message = 'hello!';

typeof message; // => 'string'


B) Numbers:


const number = 5;

typeof number; // => 'number'

typeof NaN; // => 'number'


C) Booleans:


const ok = true;

typeof ok; // => 'boolean'


D) Symbols:


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'


What about the type of null? Uh, that's a nasty one!

1.1 typeof null

As mentioned in the previous section, typeof of an object evaluates to 'object'. That's expected.

However, typeof null evaluates to 'object' as well!


const missingObject = null;

typeof missingObject; // => 'object'


As the rumors say, typeof null being 'object' was a bug in the initial implementation of JavaScript.

That's why, when using typeof to detect an object, be sure to check againts null additionally:


function isObject(object) {

return typeof object === 'object' && object !== null;

}

isObject({ name: 'Batman' }); // => true

isObject(15); // => false

isObject(null); // => false


Follow my post Everything about null in JavaScript to read more about null in JavaScript.

1.2. typeof and not defined variables

While usually typeof expression determines the type of expression, you can use typeof also to determine if a variable is defined or not.

JavaScript throws a reference error if you access a variable that is not defined:


// notDefinedVar is not defined

notDefinedVar; // throws ReferenceError


But typeof has a nice property — a reference error is not thrown when typeof evaluates the type of a not defined variable:


// notDefinedVar is not defined

typeof notDefinedVar; // => 'undefined'


The variable notDefinedVar is not defined in the current scope. However, typeof notDefinedVar doesn't throw a reference error, and evaluates to 'undefined' string.

You can use typeof to detect if a variable is not defined: typeof myVar === 'undefined' evaluates to true if myVar is not defined.

Follow the post 3 Ways to Check if a Variable is Defined in JavaScript to read more about defined/not defined variables.

2. instanceof operator

The usual way to use a JavaScript function is to invoke it by adding a pair of parentheses after its name:


function greet(who) {

return `Hello, ${who}!`;

}

greet('World'); // => 'Hello, World!'


greet('World') is a regular function invocation.

But JavaScript functions can do more: they can even construct objects! To make a function construct objects, just use new keyword before the regular function invocation:


function Greeter(who) {

this.message = `Hello, ${who}!`;

}

const worldGreeter = new Greeter('World');

worldGreeter.message; // => 'Hello, World!'


new Greeter('World') is a constructor invocation that creates the instance worldGreeter.

How can you check in JavaScript that a certain instance was created with a certain constructor? Welcome instanceof operator:


const bool = object instanceof Constructor;


where object is an expression that evaluates to an object, Contructor is a class or function that constructs objects. instanceof evaluates to a boolean.

worldGreeter instance was created using Greeter constructor, so worldGreeter instanceof Greeter evaluates to true.

Starting ES2015, a better way to construct objects is by using the class syntax. For example, let's define a class Pet and then created an instance of it myPet:


class Pet {

constructor(name) {

this.name = name;

}

}

const myPet = new Pet('Lily');


new Pet('Lily') is a construction invocation that creates an instance myPet.

Since myPet was constructed using Pet class — const myPet = new Pet('Lily')myPet instanceof Pet also evaluates to true:


myPet instanceof Pet; // => true


However, a plain object isn't an instance of Pet:


const plainPet = { name: 'Zoe' };

plainPet instanceof Pet; // => false


As for more practical examples, you may find instanceof useful to determine the built-in special instances like regular expressions, arrays:


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 and the parent class

Now the class Cat extends the parent class Pet:


class Cat extends Pet {

constructor(name, color) {

super(name);

this.color = color;

}

}

const myCat = new Cat('Callie', 'red');


As expected, myCat is an instance of Cat class:


myCat instanceof Cat; // => true


But at the same time, myCat is also an instance of the base class Pet!


myCat instanceof Pet; // => true


In simple words, object instanceof Constructor evaluates to true if object is an instance of Constructor, but also if Constructor is the parent class of instance's class.

3. Summary

JavaScript is a loosely-typed language, meaning that there is no restriction on what type a variable can have.

Thus, sometimes, you have to check what type the variable has.

typeof expression is the operator that lets you determine the type of expression. typeof evaluates to one of the values: 'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'.

typeof null evaluates to 'object', thus the correct way to use typeof to detect an object is typeof object === 'object' && object !== null.

instanceof operator let's identify the instance's constructor. object instanceof Constructor evaluates to true if object is an instance of Constructor.

Quiz: What is the built-in constructor for which instanceof for any object returns true?