DEV Community

Cover image for [freeCodeCamp] Basic JavaScript - Loops
Prashant Sharma
Prashant Sharma

Posted on • Originally published at gutsytechster.wordpress.com

[freeCodeCamp] Basic JavaScript - Loops

Hey fellas! Let's keep continue what we've learned in the previous posts. This is another post in our JavaScript learning via freeCodeCamp. In this post, we are going to cover various loop constructs, JavaScript provides us with. How one uses them and implements them.

Let's start with the post.

Loops

Loops are basically used when we want to run some piece of code multiple times. There are various ways to achieve that. Let's discuss them separately

  • for loop

The for loop is one of the commonly used loops in any programming language. The for loop has a definite structure which is

for ([initialization]; [condition]; [final-expression])

There are three main components to the for loop which are - initialization, condition, and final-expression. Each of these expressions is optional to be used.

  • The initialization is executed only once before the loop executes. It is basically the initialization of the loop variable.
  • The condition is the statement which is executed from the starting to the end of the loop. The loop will keep executing until this condition evaluates to true. Once this condition evaluates to false, the loop will be terminated.
  • The final-expression is executed at the end of each loop iteration, which changes the loop variable.

Let's see an example

var sum = 0;
for( var i = 0; i < 5; i++){
  sum += i;
}

The above loop will execute 5 times, adding the current value to i to the sum in each iteration.

  • We initialize the loop variable i with 0.
  • It'll then check for the condition i < 5.
  • As the condition evaluates to true, it enters the loop body and adds the value of i to sum by executing sum += i statement.
  • As soon as the last statement ends, the control goes to the final-expression i.e. i++ which increments i by 1.
  • After this, the condition is checked again with the updated value of i and the loop keeps on executing until the condition evaluates to false.
  • In the last iteration, the value of i would be 5. This would fail the condition i < 5 and the control will come out of the loop.

At the end of the loop, the sum will hold the value 0+1+2+3+4 i.e. 10.

  • while loop

The while loop runs repeatedly as long as a specified condition evaluates to true. Once it returns false, the execution stops. The above example can also be written using the while loop as

var sum = 0;
var i = 0;
while (i < 5) {
  sum += i;
  i++;
}

Let's break it down into smaller steps

  • We set the variable i = 0, which act as an initialization step just as in for loop.
  • We run the while loop until the value of i is less than 5.  The condition i < 5 can be seen as the condition expression like in for loop.
  • We define the final-statement i.e. i++ which must be executed so that the loop variable changes and condition evaluates to false at some point in time.

Make sure to update the loop variable within the body of the loop itself. If you don't, the loop condition will never evaluate to false and the loop will be executed infinitely.

  • do...while loop

Apart from the for and while loops, JavaScript also offers a do...while loop. It is called so because it do the one pass of the loop at least once irrespective of the condition and then keep on executing till the while condition evaluates to true.

Let's re-write the above example as

var sum = 0;
var i = 1;
do{
  sum += i;
  i++;
} while (i < 0);

Here, if you would notice, the condition i < 0 will be false when i = 1. However, the loop will still execute once. The first iteration would execute irrespective of the condition. Once the flow reaches the while condition, the loop terminates.

I hope, you understood the difference between the normal while and do...while loop. The while loop in such case would've aborted the loop without executing at all.

Notice the semicolon(;) after the while condition. You should end a do...while loop like this.


Any of the loop's final statement doesn't always need to increment by 1. It can be i-- or i+=2  etc. i.e. it can be any valid expression. Just make sure that this always leads to the loop condition to evaluate to false at some point in time.

Iterating through an array

Iterating an array is one of the most common and widely used tasks to do, which involves the usage of loops. One can do that using the for loop as

var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

The above piece of code would print each element of the array to the console. Notice the condition i < arr.length, we are not using <= because the last element of the array will have an index length - 1.

Nesting for loops

The for loops can be nested to iterate through a multi-dimensional array. Suppose we have an array

var arr = [
  [1,2], [3,4], [5,6]
];

If we want to print each element of the sub-array, The approach would be to first iterate over the outer array using some loop variable, let's say i. Now for each arr[i] which would be an array itself, for e.g. arr[0] = [1, 2], we'll take another loop variable j, which would iterate through the inner arrays.

Let's code it down to understand bit clearly

for (var i = 0; i < arr.length; i++){
  for (var j = 0; j < arr[i].length; j++){
     console.log(arr[i][j]);
  }
}

Did you understand? I am sure the outer loop would not be an issue. While going through the inner loop, we go through the length of each sub-array i.e. arr[i].length and further, we access each individual element of arr using the nested bracket notation.
For e.g. arr[0][0] would be 1. Similarly, arr[0][1] would be 2. Using the same pattern, we print out each element to the console.

Conclusion

In the end, we learned various ways to implement loops in JavaScript and performing iterations through an array. Loops are one of the basic fundamentals of any programming language and are useful in daily programming.

References

Let’s meet next time with another JavaScript post covering some other fundamentals. Till then be curious and keep learning.

Top comments (0)