...for the loop | Dale Greve

…for the loop

In JavaScript, a for loop is a control flow statement that allows you to repeat a block of code a specified number of times. Blow is the syntax for a for loop in:

The syntax is similar to a for statement in that it is checks for some type of condition and executes a command. Three pieces separated by semicolons are needed to create the for loop.

  1. The initialization value (generally a variable)
  2. Condition when to run the loop, is a boolean expression
  3. How to increment the value each loop

The following code with log “Hello World” to the console 10x and then stops. It sets the a variable (i) with an initial value of 1, then tells the code to run the loop if i is less than or equal to 10, the final piece increases i by 1 each loop.

for (let i = 1; i<= 10, i++) {
console.log("Hello World!")

You can also use a for loop to iterate over the elements in an array. Here is an example of a loop that prints out the elements of an array:

The for loop is best used when you have a known start and end point. When you have something that has an unkown outcome a while loop would be used.

const fruits = ['apple', 'banana', 'mango', 'orange'];

for (let i = 0; i < fruits.length; i++) {

This loop will output the elements of the fruits array to the console, one element per line. The counter variable i is initialized to 0, and the loop continues as long as i is less than the length of the fruits array. After each iteration, i is incremented by 1.