Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
NaN and Infinity example in JavaScript
In JavaScript, NaN (Not-a-Number) and Infinity are special numeric values that represent invalid or infinite calculations. Understanding these values is crucial for handling mathematical operations and validation.
What is NaN?
NaN represents a value that is "Not-a-Number". It occurs when a mathematical operation fails or produces an undefined result.
NaN Examples
Number("Hello") = NaN
Math.sqrt(-1) = NaN
0 / 0 = NaN
parseInt("abc") = NaN
What is Infinity?
Infinity represents a number greater than any other number. It can be positive or negative.
Infinity Examples
1 / 0 = Infinity -1 / 0 = -Infinity Number.POSITIVE_INFINITY = Infinity Number.NEGATIVE_INFINITY = -Infinity
Checking for NaN and Infinity
JavaScript provides built-in functions to detect these special values:
Testing NaN and Infinity
isNaN(NaN) = true Number.isNaN(NaN) = true isFinite(Infinity) = false Number.isFinite(Infinity) = false
Key Differences
| Value | When It Occurs | Detection Method |
|---|---|---|
NaN |
Invalid mathematical operations | Number.isNaN() |
Infinity |
Division by zero (non-zero numerator) | !Number.isFinite() |
-Infinity |
Negative division by zero | !Number.isFinite() |
Conclusion
NaN occurs from invalid operations while Infinity results from division by zero. Use Number.isNaN() and Number.isFinite() to properly detect these special values in your applications.
Advertisements
