Do the counters of the for loop work outside of it?

  • 0
    Let's say I have 5 separate cycles. Is it possible to create a counter i in each of them, or is it necessary to come up with a different name for the counter every time? Since in the second cycle the variable i will have the value that it received in the first cycle, and in the third cycle it will have the value that it acquired in the second cycle and so on.
    JavaScript Adam Shields, Jun 16, 2020

  • 4 Answers
  • 0
    Loop counter variables only live in the loop.
    Hanna Davies

  • 0
    Well damn, this is the basics. Explained in any tutorial.

    Let and const are block-scoped. So, in this case, each cycle will have its own variable.

    In the case of var, the variable will remain available after the loop ends. Its value will be equal to the last iteration of the loop.

    If a new loop follows, then it doesn't matter if the variable was previously declared. It is still initialized with the starting value ( var i = 0; ).

  • 0
    JavaScript runs code in single threaded mode. If you have several for going one after the other, then they will be executed sequentially, there will be no such thing that one for will interfere with the other. Exception, if one for is nested in another, then yes, so that there are no problems, you need to give different names to the counters.
    Scarlett Clarke

  • 0
    JavaScript fundamentally goes against most other languages, and the scope of var declared for a loop is the entire method, not just the loop operator. Only recent additions like let have narrowed the scope.

    Is it possible to make a counter i in each of them

    Felix Carrillo

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!