Infinity and NaN in JavaScript: Usage and Examples
In JavaScript,
Infinity represents a value larger than any number, often the result of dividing by zero, while NaN means "Not a Number" and indicates an invalid or undefined numerical operation. Both are special numeric values with unique behaviors used to handle exceptional cases in calculations.Syntax
Infinity is a global property representing an infinite numeric value. NaN is a global property representing an invalid number result.
You can use them directly or get them as results of operations:
Infinity- a numeric value representing infinity.NaN- a special value indicating an invalid number.
javascript
console.log(Infinity); console.log(NaN); console.log(1 / 0); // Infinity console.log('a' * 3); // NaN
Output
Infinity
NaN
Infinity
NaN
Example
This example shows how Infinity and NaN appear in calculations and how to check for them.
javascript
const positiveInfinity = 1 / 0; const negativeInfinity = -1 / 0; const notANumber = 'hello' * 5; console.log('Positive Infinity:', positiveInfinity); console.log('Negative Infinity:', negativeInfinity); console.log('NaN:', notANumber); // Checking values console.log('Is NaN:', Number.isNaN(notANumber)); console.log('Is finite:', Number.isFinite(positiveInfinity));
Output
Positive Infinity: Infinity
Negative Infinity: -Infinity
NaN: NaN
Is NaN: true
Is finite: false
Common Pitfalls
Common mistakes include confusing NaN with other falsy values and using equality checks that don't work as expected.
NaN === NaNisfalse, so useNumber.isNaN()to check forNaN.- Dividing by zero returns
Infinity, which is a number, not an error. - Using
isNaN()(global) can give unexpected results because it converts values before checking.
javascript
console.log(NaN === NaN); // false (wrong way) console.log(Number.isNaN(NaN)); // true (correct way) console.log(isNaN('hello')); // true (global isNaN converts string) console.log(Number.isNaN('hello')); // false (does not convert) console.log(1 / 0); // Infinity (not an error)
Output
false
true
true
false
Infinity
Quick Reference
| Concept | Description | Check Method |
|---|---|---|
| Infinity | Represents a value larger than any number | Use Number.isFinite() to check if not infinite |
| -Infinity | Represents negative infinity | Same as Infinity check |
| NaN | Result of invalid numeric operations | Use Number.isNaN() to check |
| Division by zero | Returns Infinity or -Infinity, not error | No error thrown |
| NaN equality | NaN === NaN is false | Use Number.isNaN() |
Key Takeaways
Infinity represents an unbounded number, often from division by zero.
NaN means an invalid number result and must be checked with Number.isNaN().
Never use === to check for NaN because it always returns false.
Division by zero returns Infinity, not an error.
Use Number.isFinite() to test if a value is a normal number, not Infinity or NaN.