JAVASCRIPT: For Loops



Loop Basics

It is often necessary to repeat certain blocks of code for a specified(or unspecified) number of times. We use a control structure known as a loop to accomplish this. Every loop has four basic parts:

  1. Loop control variable declaration/initialization
  2. Loop condition
  3. Control variable alteration/reassignment
  4. Loop body(statements to be repeated)

Loops come in two basic varieties:


Regardless of whether you loop is pre or post test, it also has another type of classification: counting or sentinal. Counting loops are set to execute a certain number of times. Loops that depend on user input are called sentinal loops, and will execute as many times as necessary until the user enters a predefined value.

JavaScript also has two loop keywords that can help control the flow of the loop. Those words are
break
and
continue
. Break will immediately send control to the code following the loop. Continue sends control immediately to the top of the loop.

For Loops

A for loop, like any loop has 4 parts: the loop control variable start value, condition, code to be executed and an alteration of the control variable. “for” loops are popular because the combine 3 of these four items into one line. Here is an example of a for loop:
for(let x=0; x<5; x+=1){
	//code
}

This is read, for the variable x starting with a value of 0 and as long as x is less than 5, execute the code and increment x by 1 each time.

So, to print 5 hello messages, we would write:
for(let x=1; x<=5; x+=1){
	document.getElementById('output').innerHTML+=“Hello”;
}