codedamn logo
codedamn

For loops in JavaScript

  • Vishnupriya's profile image
    Vishnupriya
    Team codedamn
For loops in JavaScript

Loops in JavaScript allow us to do something repeatedly in a quick and easy way. We use loops to access the items of an array or an object. Every single loop is known as an iteration

Some of the common types of loops are –

  • For
  • For / in
  • For/of
  • While
  • Do / while

Let us take an example and understand how loops are helpful to do something repeatedly in an effective way.

1. Manual method

<script type = "text/javascript"> 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
document.write("Codedamn\n"); 
< /script>

2. Using loops

<script type = "text/javascript"> 
var i; 
for (i = 0; i < 10; i++)  
{ 
    document.write("Codedamn\n"); 
} 
< /script>

Let us discuss some of the loops in detail.

For loop

Firstly, let us understand the syntax of for loop.

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1

It is the initialization of the loop. It runs before the loop starts its execution. In the whole process, it runs only one time. The variables that are created in the initialization step are scoped to the loop. It is often used for creating counters. They are destroyed after the loop completes its execution.

Statement 2

It is the condition of the loop. This condition is checked before the execution of every iteration. When the condition given is satisfied, the loop is executed but when the condition given is not satisfied, the loop stops its execution.

Statement 3

It is the final expression of the loop. It is run after every iteration in order to increment or decrement a counter. 

After all of these 3 statements, we usually write the code block that needs to be executed. We can use a break statement to exit the loop prior before the loop stops. Let us take some examples and understand the working of the for loop.

Example 01:

Print numbers from 0 to 10
for (let i = 0; i < 11; i++) {
  console.log(i);
}
// Output:
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10

Example 02:

for (let i = 1; i < 10; i += 2) {
  if (i === 9) {
    break;
  }
  console.log('Total fruits: ' + i);
}
// Output:
// Total fruits: 1
// Total fruits: 3
// Total fruits: 5
// Total fruits: 7

Example 03:

Sum of 100 natural numbers

let sum = 0;
const n = 100
// looping from i = 1 to n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
    sum += i;  // sum = sum + i
}
console.log('sum:', sum);
// Output:
// sum: 5050

We can iterate over an array with the help of a for loop. A for loop can iterate over elements of the array in a very effective way. Let us take an example to understand how we can access elements of an array.

const array1 = [1,2,3,4,5];
for(let i = 0; i < array1.length; i++) {
    console.log(array1[i]);
}
//Output
// 1
// 2
// 3
// 4
// 5

The array1.length is the number of elements present in the array. The condition array1.length tells the loop when to stop.

When you try to reference an element of an array that is not present, it returns undefined.

const array1 = [ 1, 2, 3 ];
for (let i = 0; i <= array1.length; i++) {
  console.log(array1[i]);
}
// Output:
// 1
// 2
// 3
// undefined

For/in loop

A for/in loop in JavaScript is used to iterate over the properties of an object. For each property, the statement in the loop is executed. This loop iterates over the keys of an object which has an enumerable property set to true. The values of keys of an object have four attributes that are enumerable, configurable, value, and writable. When enumerable is set to true, we can iterate over that property. Let us take some examples and understand the working of the for/in loop.

Example 01:

const country = {
  a: "India",
  b: "france",
  c: "Germany"
};
for (let key in country) {
  console.log(key + ": " + country[key]);
}
// Output:
// a: India
// b: france
// c: Germany

We can also use this loop to iterate over an array.

Example 02:

const array = [1, 2, 3];
for (const i in array) {
  console.log(i);
}
// Output:
// 0
// 1
// 2

For/of loop

The for/of loop is used to iterate over the values of many iterables such as arrays, sets, maps, etc. The statement in the loop is executed for the values in the iterables. 

Example 01: Iterate over an array

const arr = [ "January", "February", "March" ];
for (let i of arr) {
  console.log(i);
}
// Output:
// January
// February
// March

Example 02: Iterate over a set

const s = new Set();
s.add("january");
s.add("february");
for (let n of s) {
  console.log(n);
}
// Output:
// january
// february

Example 03: Iterate over a map

const m = new Map();
m.set(1, "january");
m.set(2, "february");
for (let n of m) {
  console.log(n);
}
// Output:
// [1, january]
// [2, february] 

Conclusion

In this blog, we learned how to construct for loops in JavaScript that consist of the for, for…of, and for…in statements. I am sure that this blog has added to your knowledge of JavaScript. This was all about for loop in JavaScript. If you want to learn more about javascript, do check out the article and course on Codedamn of javascript.

User avatar