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

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

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 Type checking in JavaScript: typeof and instanceof operators 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()
Infinity in JavaScript
Dmitri Pavlutin · 2019-12-17 · via Dmitri Pavlutin Blog

Infinity in JavaScript is a special number with an interesting property: it's bigger than any finite number.

Without knowing the properties of Infinity in advance, you might be surprised how infinite numbers perform in conditionals and arithmetical operations.

Let's look at the properties of Infinity number in JavaScript, understand the use cases and be aware of common pitfalls.

1. The definition of Infinity

The ECMAScript standard describes Infinity as follows:

There are two other special values, called positive Infinity and negative Infinity. [...] Note that these two infinite Number values are produced by the program expressions +Infinity (or simply Infinity) and -Infinity.

Which means that Infinity, as well as -Infinity (the number small than any finite number) are special values of type number:


typeof Infinity; // => 'number'

typeof -Infinity; // => 'number'


Infinity is a property on the global object. For instance in a browser:


window.Infinity; // => Infinity


Note that Number function has 2 properties holding the infinite values as well:


Number.POSITIVE_INFINITY; // => Infinity

Number.NEGATIVE_INFINITY; // => -Infinity


2. The properties of Infinity

Infinity is bigger than any finite number.

Let's see some examples:


Infinity > 100; // => true

Infinity > Number.MAX_SAFE_INTEGER; // => true

Infinity > Number.MAX_VALUE; // => true


Infinity has interesting effects when used as an operand in arithmetical operations like addition, multiplication and division:


Infinity + 1; // => Infinity

Infinity + Infinity; // => Infinity

Infinity * 2; // => Infinity

Infinity * Infinity; // => Infinity

Infinity / 2; // => Infinity


Some operations with Infinity result in finite numbers:

Dividing a finite number by 0 results in Infinity:

Making conceptually incorrect operations on infinite numbers results in NaN. For example, you can't divide infinite numbers, and you cannot determine if an infinite number is odd or even:


Infinity / Infinity; // => NaN

Infinity % 2; // => NaN


2.1 The negative infinity

-Infinity (the negative infinity) is smaller than any finite number.

Let's compare -Infinity with some finite numbers:


-Infinity < 100; // => true

-Infinity < -Number.MAX_SAFE_INTEGER; // => true

-Infinity < -Number.MAX_VALUE; // => true


At the same time, negative infinity is smaller than positive infinity:


-Infinity < Infinity; // => true


You might end up in negative infinity when using operands of different signs:


Infinity * -1; // => -Infinity

Infinity / -2; // => -Infinity

-2 / 0; // => -Infinity


3. Checking for Infinity

Fortunately, an infinite value equals to an infinite value of the same sign:


Infinity === Infinity; // => true

-Infinity === -Infinity; // => true


Because of different signs Infinity doesn't equal -Infinity:


Infinity === -Infinity; // => false


JavaScript has a special function Number.isFinite(value) that checks whether the provided value is finite:


Number.isFinite(Infinity); // => false

Number.isFinite(-Infinity); // => false

Number.isFinite(999); // => true


4. When to use Infinity

The infinity value is handy to initialize computations involving comparisons of numbers.

For example, when searching for a minimum value in an array, you could initialize the min variable with Inifinity.


function findMin(array) {

let min = Infinity;

for (const item of array) {

min = Math.min(min, item);

}

return min;

}

findMin([5, 2, 1, 4]); // => 1


On first for() iteration the minimum value becomes the first item because any finite value is smaller than Infinity.

5. Pitfalls of Infinity

Most likely you won't work directly with Infinity values so often. However, it worth knowing when the infinite values could appear.

5.1 Parsing numbers

Let's say JavaScript uses an input (POST request, value from an input field, etc) to parse a number. In simple cases it would work fine:


// Parses the float number

parseFloat('10.5'); // => 10.5

// Indicates an invalid number

parseFloat('ZZZ'); // => NaN


Care must be taken because 'Infinity' string is parsed by parseFloat() as an actual Infinity number:


parseFloat('Infinity'); // => Infinity


It should be a validation error when the user introduces the 'Infinity' string into a numeric input field.

An alternative could be parseInt() to parse integers. It doesn't recongize 'Infinity' as an integer:


parseInt('10', 10); // => 10

parseInt('Infinity', 10); // => NaN


5.2 JSON serialization

JSON.stringify() serializes an Infinity number to null.


const worker = {

salary: Infinity

};

JSON.stringify(worker); // => '{ "salary": null }'


salary property is Infinity. But when stringified to JSON, "salary" becomes null.

5.3 Max number overflow

Number.MAX_VALUE is the biggest float number in JavaScript.

Trying to use a number even bigger than Number.MAX_VALUE, JavaScript transforms such number to Infinity:


2 * Number.MAX_VALUE; // => Infinity

Math.pow(10, 1000); // => Infinity


5.4 Math functions

Some functions of Math namespace in JavaScript can return infinite numbers.

Here are a few examples:


const numbers = [1, 2];

const empty = [];

Math.max(...numbers); // => 2

Math.max(...empty); // => -Infinity

Math.min(...numbers); // => 1

Math.min(...empty); // => Infinity


Math.max() when invoked without arguments returns -Infinity, and Math.min() correspondingly Infinity. That could be a surprise if you try to determine the max or min of an empty array.

Here's an interesting math discussion why that happens.

6. Key takeaway

Infinity in JavaScript represents the concept of an infinite number. Any finite number is smaller than Infinity, and any finite number is bigger -Infinity.

Comparing infinite values in JavaScript is easy: Infinity === Infinity is true. The special function Number.isFinite() determines if the supplied argument is a finite number.

You can initialize variables with Infinite when starting an algorithm that involves a comparison of numbers. A use case is finding the minimum of an array.

Care must be taken with Infinity when parsing numbers from inputs: Number('Infinity'), parseFloat('Infinity') return the actual Infinity number. When serialized with JSON.stringify(), the infinite number becomes null.

Hopefully, after reading my post you have a better idea of infinite numbers!