Understanding Infinity, Negative Infinity, and NaN in JavaScript

Today, we will dive into a topic that can sometimes leave developers scratching their heads: Infinity, Negative Infinity, and NaN.

Whether you're a seasoned developer or just starting, it's essential to understand how these values work to write more robust and error-free code.

Let's demystify these JavaScript values!

Infinity and Negative Infinity

When you perform a numeric operation and the result is larger than the largest number that can be represented, JavaScript returns a special value called Infinity.

Similarly, when the absolute value of a negative number is bigger than the largest negative number that JavaScript can handle, JavaScript will return a value of -Infinity.

It's important to note that adding, subtracting, multiplying, or dividing them by anything results in an infinite value. So, be careful when dealing with these values and ensure that your code can handle them correctly.

1 / 0; // Infinity

Number.MAX_VALUE * 2; // Infinity

-1 / 0; // -Infinity

Number.MIN_VALUE * 2; // -Infinity

NaN

Another important value to be aware of in JavaScript is NaN, which stands for Not a Number. Zero divided by zero does not have a defined value, so JavaScript returns NaN. This value also arises if you attempt to divide infinity by infinity, take the square root of a negative number, or use arithmetic operators with non-numeric operands that cannot be converted to numbers.

0 / 0; // NaN

Infinity / Infinity; // NaN

Math.sqrt(-1); //NaN

One thing to keep in mind is that NaN does not compare equal to any other value, not even itself. This means that you can't use x === NaN to determine if a variable x is NaN.

Functions that can help you out

To make things easier, there are a few functions that can help you out when dealing with these special values.

  • The isNaN() function returns true if its argument is NaN or a non-numeric value that cannot be converted to a number.
  • The Number.isFinite() function returns true if its argument is a number other than NaN, Infinity, or -Infinity.

By keeping these values in mind and using suitable functions to handle them, you can ensure that your code works correctly and efficiently.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda