The same web page is used to demonstrate three different kinds of for loops. As usual, the HTML code sets everything up.
From this example, it's easy to see why it's a good idea to write the HTML first. The HTML code gives me a solid base for the program, and it also provides a good outline of what JavaScript code I'll need. Clearly this page call for four JavaScript functions, init(), count(), back(), and byFive().
It seems a waste to create a variable for output three different times. Instead, it is better to make single global output variable available to all functions, and attach the variable to that element once when the page loads.
In order to understand why this is necessary, it's important to discuss an idea called variable scope. Generally, variables are created inside functions. As long as the function is running, the variable still exists. However, when a function is done running, all the variables created inside that function are instantly destroyed. This prevents functions from accidentally changing the variables in other functions. Practically, it means you can think of each function as a separate program.
However, sometimes you want a variable to live in more than one function. The output variable in the forLoop.html page is a great example because all of the functions will need it. One solution is to create the variable outside any functions. Then all the functions will have access to it.
The init() function is called when the body loads. Inside that function, I assign a value to the global output variable. Here's how the main JavaScript and the init() method code looks:
This code creates output as a global variable, and then attaches it to the output div after the page has finished loading.
Dreamweaver gave error for </script>, yet the program worked.