Looping is an essential part of coding. Looping allows us to execute code as many times as needed, each time with a different value. This minimizes the lines of code and can be used as a powerful tool when optimizing code.Today we are going to discuss a few different ways to Loop in Javascript and hopefully understand the difference and power in each.

For statement

for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement

The first loop that we will discuss is a pretty common way to loop through data. This loop starts by initializing an expression if any. This is where you can initialize counters and declare variables as shown below. After the initial expression, the for loop takes in a condition expression. The condition expression is evaluated and if false for loop terminates. If the condition returns true, then the loop continues to execute. When true the statement would be what executes. The last expression it accepts is an increment expression. This expression is responsible for updating the count initialized.

for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
console.log('Walking east one step');
}

For in statement

for (variable in object)
statement

The For in loop is used to iterate over enumerable property names of an object using a variable. The variable is then used to execute the statement. For in is better to use with objects because the key is assigned to the variable which can be really useful. However it can still be used with an array, the key will be substituted with the index.

const object = { a: 1, b: 2, c: 3 };for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

For of statement

for (variable of iterable) {
statement
}

The for of loop is used to loop over iterable objects(built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterable). The value is assigned a variable which is used to execute the statement. This helps us skip referencing the index in the array in order to get the value. Now we can skip a line of code or just repetitive indexing.

const array1 = ['a', 'b', 'c'];for (const element of array1) {
console.log(element);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"

The Small Difference

The for of statement is very similar to the for in statement. One of the biggest differences is that the variable in the for of statement is used to represent the value rather than the key. Rule of thumb, use for in for objects and for of for other data structures.

Happy Coding!