Repeat

For Loop

JavaScript

 

For loop

ECMAScript 5
for (var count=5; count>0; count--) {
  
    console.log(count);
  
}

for statement is a handy syntax for iterating through arrays and iteratable objects. Below is the most common syntax used:

for (<initialize>; <condition>; <modification>) {
    <code block>
}

The for loop above executes in the order below:

  1. Execute <initialize>
  2. If <condition> evaluates to true execute the <code block>
  3. Execute <modification>
  4. Go to Step 2

This will print 5 4 3 2 1 on Console.

 

Single For loop Statement

ECMAScript 5
for (var count=5; count>0; count--)
    console.log(count);

If you only have one statement in your for block, you can drop the curly braces { }.

This will print 5 4 3 2 1 on Console.

 

For in loop

ECMAScript 5
var obj = {
  name: 'Sam', 
  age: 21
};

for (prop in obj) {
    console.log(prop + ":" + obj[prop]); 
}

for in iterates through an object properties.

This will print name:Sam age:21 on Console.

 

For of loop

ECMAScript 2015
var arr = [10, 11, 12];

for (i of arr) {
    console.log(i);  
}

for of iterates through iteratable objects including:

  • Strings
  • Arrays,
  • Array-likes (arguments or NodeList)
  • TypedArrays
  • Maps
  • Sets
  • user-defined iterables.

This will print 10 11 12 on Console.

 

ForEach loop

ECMAScript 5
var arr = [10, 11, 12];

arr.forEach(function(element, index) {
    console.log(index + ":" + element);
});

Array has a handy method called forEach which lets you to iterate through its elements in an elegant syntax.

This will print 0:10 1:11 2:12 on Console.