JavaScript For Loop

This is a preview lesson
Register or sign in to take this lesson.
In this lesson, we will learn about different types of  javascript for loop statement available. For loops are a type of programming statement that inspects every element an object contains. There are different types of for loop available in javascript.For every type of for loop, the structure of the for loop statement is the same.

Types of Javascript For Loop

Simple For Loop

In a simple for loop, a variable is incremented each time the loop is executed. In order to keep track of every nth element in an object, the variable acts as a counter.

Syntax,

for (initialization; condition; finalExpression) {
  // code
}

Example,

for (let i = 0; i < 5; i++) {
    console.log(i);
}

In the above example, the for loop statement is executed until the value of i is less than 5. In each iteration, its logs the value of i in the console.

For-In Loop

The For-In loop traverses the set of enumerable properties keyed by the string values of an object. For each property, the code in the code block is executed.

Syntax,

for (property in object) {
  // code
}

Example,

const sports = {
  a: "Football",
  b: "Cricket",
  c: "Baseball"
};

for (let key in sports) {
  console.log(key + ": " + sports[key]);
}
// Output:
// a: Football
// b: Cricket
// c: Baseball

Here, the For-In loop iterates over all the items in the sports objects and logs the key of the object along with its respective values as shown in the above output section.

For-Of Loop

A For-Of statement creates a loop iterating over a collection of iterable objects, such as the built-in String object, Array, TypedArray, Set, Map, and Map iterables.  The iteration hook invokes statements to be executed for each of the distinct properties of the object.

Syntax,

for (variable of object) {
  // code
}

Example,

// Iterate over an array
const person = [ "Fred", "Tom", "Bob" ];

for (let i of person) {
  console.log(i);
}

In the above example, the For-Of loop iterates over all the elements of the array, and individually logs the element in the console.

// Iterate over a string
const iterable = 'hello';

for (const value of iterable) {
  console.log(value);
}
//Output
//h
//e
//l
//l
//o

In the above example, the For-Of loop iterates over a string and logs the single character of the string.

Conclusion

In this article, we learn about some of the javascript for loops available with the help of some examples. To learn more about javascript visit here.