user5870134
user5870134

Reputation:

To infinity and beyond in JavaScript

In JavaScript there is a global property named Infinity, and to the best of my knowledge the value of Infinity is 1.797693134862315E+308 (I may be wrong there).
I also understand that any number larger than 1.797693134862315E+308 is considered a "bad number", if this is the case then why does my code (below) work perfectly fine?

This is my code:

// Largest number in JavaScript = "1.797693134862315E+308"
// Buzz = Infinity + "0.1"
var buzz = 1.897693134862315E+308;

// Why is no error is thrown, even though the value of "buzz" is a bad number...
if(buzz >= Infinity) {
  console.log("To infinity and beyond.");
}

The output is:

=> "To infinity and beyond."

There is a working example of my code on Repl.it

Upvotes: 0

Views: 474

Answers (1)

Pointy
Pointy

Reputation: 413720

  1. The value of Infinity is Infinity. It is not the number you mention, which is Number.MAX_VALUE. Infinity is a constant that has meaning in the number system.
  2. Adding a small number to a large floating-point value doesn't overflow because the number is a large floating-point value and that's how floating point works. If you add a large enough number to a large number, as in

    Number.MAX_VALUE + Number.MAX_VALUE
    

    then it will overflow and you'll get Infinity.

You can read more about IEEE 754 Floating Point math on Wikipedia or various other sources.

Upvotes: 2

Related Questions