Does this for
loop ever stop?
for (var i=0; 1/i > 0; i++) {
}
If so, when and why? I was told that it stops, but I was given no r
The condition 1/i > 0
will always evaluate to true:
Initially it's true because 1/0
evaluates to Infinity and Infinity > 0
is true
It stays true since 1/i > 0
is true for all i < Infinity
and i++
never reaches Infinity
.
Why does i++
never reach Infinity
? Due to the limited precision of the Number
datatype, there is a value for which i + 1 == i
:
9007199254740992 + 1 == 9007199254740992 // true
Once i
reaches that value (which corresponds to Number.MAX_SAFE_INTEGER + 1
), it will stay the same even after i++
.
We therefore have an infinite loop.
Why is 9007199254740992 + 1 == 9007199254740992
?
JavaScript's Number
datatype is actually an 64-bit IEEE 754 double precision float. Each Number
is disassembled and stored as three parts: 1-bit sign, 11-bit exponent, and 52-bit mantissa. Its value is -1 sign × mantissa × 2 exponent.
How is 9007199254740992 represented? As 1.0 × 2 53, or in binary:
Incrementing the mantissa's least significant bit, we get the next higher number:
The value of that number is 1.00000000000000022… × 2 53 = 9007199254740994
What does that mean? Number
can either be 9007199254740992 or 9007199254740994, but nothing in between.
Now, which one shall we chose to represent 9007199254740992 + 1? The IEEE 754 rounding rules give the answer: 9007199254740992.