The standard for loop in JavaScript counts the values between 1 and 10. The “count to ten” button triggers the count()function for your HTML5 and CSS3 programming. Here's the code for count():
function count(){ output.innerHTML = "; for (i = 1; i <= 10; i++){ output.innerHTML += i + "<br />"; } // end for loop } // end count
Although the count() function clearly prints ten lines, it only has one line that modifies the output div. The main code repeats many times to create the long output.
You can use the output var immediately.
Because output is a global variable and it has already been created, you can use it instantly. There's no need to initialize it in the function.
Clear the output.
Set output.value to the empty string (“”) to clear the output. This will destroy whatever text is currently in the div.
Start a for loop.
The for loop is a special loop used to repeat something a certain number of times. For loops have three components: initialization, comparison, and update.
Initialize your counting variable.
A for loop works by changing the value of an integer many times. The first part of a for loop initializes this variable (often called i) to a starting value (usually 0 or 1).
Specify a condition for staying in the loop.
The second part of a for statement is a condition. As long as the condition is true, the loop will continue. As soon as the condition is evaluated as false, the loop will exit.
Change the variable.
The third part of a for statement somehow changes the counting variable. The most common way to change the variable is to add one to it. The i++ syntax is a shortcut for “add one to i.”
Build a code block for repeated code.
Use braces and indentation to indicate which code repeats. All code inside the braces repeats.
Inside the loop, write to the output.
On each iteration of the loop, add the current value of to the output div's innerHTML. Also add a break (
) to make the output look better. When you add to an innerHTML property, you're writing HTML code, so if you want the output to occur on different lines, you need to write the HTML to make this happen.Close the loop.
Don't forget to end the loop, or your program will not run correctly.