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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

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 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() 5 JavaScript Scope Gotchas
Why Math.max() Without Arguments Returns -Infinity
Dmitri Pavlutin · 2021-05-18 · via Dmitri Pavlutin Blog

Math.max() is a built-in JavaScript utility function that determines the maximum number from the arguments.

For example, let's determine the maximum of the numbers 1, 2 and 3:


Math.max(1, 2, 3); // => 3


As expected, 3 is the maximum of 1, 2, and 3.

What would happen if Math.max() is invoked with just one argument:

As expected, the maximum of one number is the number itself.

But what would happen if you invoke Math.max() without arguments at all?


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


While it might be unexpected at first, but calling Math.max() without arguments returns -Infinity. Let's find out why it happens, and why it's important to happen this way.

1. Max of one array

Before diving into the main question (why Math.max() without args returns -Infinity), let's see how Math.max() can be used to determine the maximum number from an array.

Math.max(num1, num2, ..., numN) accepts multiple number arguments and returns the maximum number of them. Simple as a pie.

If you want to determine the maximum number of an array, then you can use the spread arguments operator on the array:


const numbers1 = [1, 2, 3];

Math.max(...numbers1); // => 3


Math.max(...numbers1) expression uses the spread syntax and returns the maximum number of numbers1 array: 3.

2. Max of 2 arrays

Now let's try something more interesting. Given two arrays of numbers, let's determine the maximum number of each array, and then determine the maximum of these 2 maximum values.

A bit overwhelming, but bear with me...


const numbers1 = [1, 2, 3];

const numbers2 = [0, 6];

const max1 = Math.max(...numbers1);

const max2 = Math.max(...numbers2);

max1; // 3

max2; // 6

Math.max(max1, max2); // => 6


The maximum number of [1, 2, 3] is 3, and of [0, 6] is corresponding 6. The max value from 3 and 6 is 6.

That's expected.

What about trying to determine the maximum of arrays if one array is empty? Let's make numbers1 an empty array and try again:


const numbers1 = [];

const numbers2 = [0, 6];

const max1 = Math.max(...numbers1);

const max2 = Math.max(...numbers2);

max1; // -Infinity

max2; // 6

Math.max(max1, max2); // => 6


Now, having the first array empty, the above code snippet correctly determines 6 as being the maximum of 2 arrays.

What's interesting is what value returns Math.max(...numbers1): being that numbers1 array is empty, this is the same as calling Math.max() without arguments. Correspondingly, this is -Infinity.

Then Math.max(max1, max2) is evaluated as Math.max(-Infinity, 6), which results in 6.

Now it's clear why Math.max() returns -Infinity when called without arguments: it's a way for the max function to be defined upon an empty set.

Making a parallel between max and addition, -Infinity for max is the same as 0 for addition.

The same behavior happens with Math.min() — it returns Infinity when called without arguments.

-Infinity, in regards to the max operation on the real numbers, is called the Identity element.

3. Conclusion

Math.max() called without arguments returns -Infinity to correctly handle the cases multiple maximum operations are performed (max of max of max...), particularly being useful when determining the max value of an empty array.

In simple words, if you're determining the maximum numbers of 2 arrays, and then determine the maximum of these maximums too, you would get the expected result.


Math.max(

Math.max(...[]), // -Infinity

Math.max(...[0, 6]) // 6

); // => 6


Challenge: Can you write a sum(num1, num2, ..., numN) function that works exactly like Math.max(), only that it summarizes its argument? What would be the identity element? Share your solution in a comment below!