0

Javascript - Loops (For, While, Do...while)

Greetings Forum. I master the subject of the three loops mentioned. First of all, I want to say that I know how to apply the three loops aforementioned. However, I have another question. //This is the for loop for (i=0; i<=100; i++) { } document.write(i + "<br/>"); I know that <<document.write(i +"<br/>") is outside of the loop therefore the result would be different than if it was inside, but I want to know the logic that gets me "101" as an answer. When <<document.write(i + "<br/>")>> is inside the loop, I understand the logic that gives me that list of numbers from 0 to 100. But can someone explain the logic when <<document.write(i + "<br/>")>> is not inside the loop? PS: By inside the loop (resp. outside of the loop), I mean inside the curly brackets (resp. outside of the curly brackets). Thank you in advance.

23rd Nov 2020, 6:48 AM
N'Guessan Armel Bénié
N'Guessan Armel Bénié - avatar
2 Antworten
+ 4
The loop is ended the first time the loop condition is false. The first number for which (i <= 100) is false is 101. So after the exit from the loop i is 101.
23rd Nov 2020, 6:55 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
+ 2
Armel Michel The reason you getting the 101 after the loop is done is that the variable "i" is globally scoped. Using the example giving you defined the variable "i" without the keyword let. If you had done so you would have seen an error message stating that i is undefined instead of 101. Defining a variable without var, let, or const makes that variable a global variable that can be used thought the code. Variables defined using let or const are block-scoped, meaning "i" is only available to code within a block, in this case, the brackets of the for-loop. While variables defined using var will be function-scoped and in this case using var will yield the results, 101. This is one of the reasons why using var is discouraged. https://www.youtube.com/results?search_query=var+let+const+javascript
23rd Nov 2020, 5:41 PM
ODLNT
ODLNT - avatar