Javascript For Loop

In this section, we will learn how a series of actions can be repeated using loops in JavaScript.


Types of Loops in JavaScript

Loops are used to execute a block of code repeatedly, until a certain condition is met. Loops can be used to execute a specific code, a specific number of times. Here's the list of loops available in JavaScript:

  • for loop - Loops through the block of code a specific number of times
  • while loop - Loops through the block of code until the condition is true
  • do while - Loops through the block of code once, and then the condition is checked. The only difference from while loop is that the code is executed first(for the first iteration) and then the condition is checked.
  • for in - Loops through the properties of an object
  • for of - Loops through the iterable objects

The For Loop


The for loop executes a block of code until a certain condition is met. Here's the syntax:



for(initialization; condition; increment){
  //Code goes here
}



Here's the purpose of the parameters in for loop:

  • Initialization - It is used to initialize a variable, and is evaluated before the first execution of the for loop
  • Condition - The condition is checked before the execution of each iteration
  • Increment - The counter is updated after execution of each iteration

The for loop is commonly used for iterating over an array. In the following example, an array is defined, and we will be traversing through the array using the for loop:



//Array defined
var cars = ['BMW', 'Audi', 'Nissan', 'Ferrari', 'Toyota'];

//Looping through all the elements
for(var i = 0; i < cars.length; i++){
  document.write('Array Value : ' + cars[i]  + '<br>');
}

Live Demo!