[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/endless-loop-error [Back]  [Original]

An occasional infinite loop
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    An occasional infinite loop

    importance: 4

    This loop is infinite. It never ends. Why?

    let i = 0;
    while (i != 10) {
      i += 0.2;
    }
    solution

    Thats because i would never equal 10.

    Run it to see the real values of i:

    let i = 0;
    while (i < 11) {
      i += 0.2;
      if (i > 9.8 && i < 10.2) alert( i );
    }

    None of them is exactly 10.

    Such things happen because of the precision losses when adding fractions like 0.2.

    Conclusion: evade equality checks when working with decimal fractions.


    Web Proxy Viewer  |  New URL  |  Original Page