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

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

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()
NaN in JavaScript
Dmitri Pavlutin · 2020-01-08 · via Dmitri Pavlutin Blog

The number type in JavaScript holds integers and floats:


const integer = 4;

const float = 1.5;

typeof integer; // => 'number'

typeof float; // => 'number'


Plus there are 2 special number values: Infinity (a number bigger than any other number) and NaN (representing "Not A Number" concept):


const infinite = Infinity;

const faulty = NaN;

typeof infinite; // => 'number'

typeof faulty; // => 'number'


While working directly with NaN is rare, it can appear surprisingly after a failed operation on numbers.

Let's take a closer look at NaN special value: how to check if a variable has NaN, and importantly understand the scenarios that create "Not A Number" values.

1. NaN number

The number type in JavaScript is a set of all number values, including "Not A Number", positive infinity and negative infinity.

"Not A Number" can be accessed using a special expression NaN, or as a property of the global object or Number function:


typeof NaN; // => 'number'

typeof window.NaN; // => 'number'

typeof Number.NaN; // => 'number'


"Not a Number" is a value that does not represent a real number, despite having number type. NaN is useful to represent faulty operations on numbers.

For example, multiplying a number with undefined is not a valid operation, thus the result is NaN:

Also trying to parse an invalid numeric string like 'Joker' results in NaN too:


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


The section 3. Operations resulting in NaN details into the operations that generate NaN.

2. Checking for equality with NaN

The interesting property of NaN is that it doesn't equal to any value, even with the NaN itself:

This behavior is useful to detect if a variable is NaN:


const someNumber = NaN;

if (someNumber !== someNumber) {

console.log('Is NaN');

} else {

console.log('Is Not NaN');

}

// logs "Is NaN"


someNumber !== someNumber expression is true only if someNumber is NaN. Thus the above snippet logs to console "Is NaN".

JavaScript has bult-in functions to detect NaN: isNaN() and Number.isNaN():


isNaN(NaN); // => true

isNaN(1); // => false

Number.isNaN(NaN); // => true

Number.isNaN(1); // => false


The difference between these functions is that Number.isNaN() doesn't convert its argument to a number:


isNaN('Joker12'); // => true

Number.isNaN('Joker12'); // => false


isNaN('Joker12') converts the argument 'Joker12' into a number, which is NaN. Thus the function returns true.

On the other side, Number.isNaN('Joker12') checks without conversion if the argument is NaN. The function returns false because 'Joker12' doesn't equal NaN.

3. Operations resulting in NaN

3.1 Parsing numbers

In JavaScript you can transform numeric strings into numbers.

For example, you could easily transform the '1.5' string into a 1.5 float number:


const numberString = '1.5';

const number = parseFloat(numberString);

number; // => 1.5


When the string cannot be converted to a number, the parsing function returns NaN: indicating that parsing has failed. Here are some examples:


parseFloat('Joker12.5'); // => NaN

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

Number('Joker12'); // => NaN


When parsing numbers, it's a good idea to verify if the parsing result is not NaN:


let inputToParse = 'Invalid10';

let number;

number = parseInt(inputToParse, 10);

if (isNaN(number)) {

number = 0;

}

number; // => 0


The parsing of inputToParse has failed, thus parseInt(inputToParse, 10) returns NaN. The condition if (isNaN(number)) is true, and number is assigned to 0.

3.2 undefined as an operand

undefined used as an operand in arithmetical operations like addition, multiplication, etc. results in NaN.

For example:


function getFontSize(style) {

return style.fontSize;

}

const fontSize = getFontSize({ size: 16 }) * 2;

const doubledFontSize = fontSize * 2;

doubledFontSize; // => NaN


getFontSize() is a function that accesses the fontSize property from a style object. When invoking getFontSize({ size: 16 }), the result is undefined (fontSize property does not exist in { size: 16 } object).

fontSize * 2 is evaluated as undefined * 2, which results in NaN.

"Not A Number" is generated when a missing property or a function returning undefined is used as a value in arithmetical operations.

Making sure that undefined doesn't reach arithmetical operations is a good approach to prevent NaN. Feel free to check "7 Tips to Handle undefined in JavaScript".

3.3 NaN as an operand

NaN value is also generated when an operand in aritemtical operations is NaN:


1 + NaN; // => NaN

2 * NaN; // => NaN


NaN spreads across the arithmetical operations:


let invalidNumber = 1 * undefined;

let result = 1;

result += invalidNumber; // append

result *= 2; // duplicate

result++; // increment

result; // => NaN


Operations on result variable are broken after invalidNumber value (which has NaN) is appended to result.

3.4 Indeterminate forms

NaN value is created when arithmetical operations are in indeterminate forms.

The division of 0 / 0 and Inifinity / Infinity:


0 / 0; // => NaN

Infinity / Infinity; // => NaN


The multiplication of 0 and Infinity:

Additions of infinite numbers of different signs:


-Infinity + Infinity; // => NaN


3.5 Invalid arguments of math functions

The square root of negative number:


Math.pow(-2, 0.5); // => NaN

(-2) ** 0.5; // => NaN


Or the lograrithm of a negative number:

4. Conclusion

"Not A Number" concept, expressed in JavaScript with NaN, is useful to represent faulty operations on numbers.

NaN doesn't equal to any value, even with NaN itself. The recommended way to check if a variable contains NaN is to use Number.isNaN(value).

Transforming numeric strings to numbers, when failed, could result in "Not A Number". It's a good idea to check whether parseInt(), parseFloat() or Number() don't return NaN.

undefined or NaN as an operand in arithmetical operations usually result in NaN. Correct handling of undefined (providing defaults for missing properties) is a good approach to prevent this situation.

Indeterminate forms or invalid arguments for mathematical functions also result in "Not A Number". But these cases happen rarely.

Here's my pragmatic advice: "Got NaN? Search for undefined!"