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
forloop
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
initializationis executed only once before the loop executes. It is basically the initialization of the loop variable. - The
conditionis the statement which is executed from the starting to the end of the loop. The loop will keep executing until thisconditionevaluates totrue. Once this condition evaluates tofalse, the loop will be terminated. - The
final-expressionis 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
iwith0. - It'll then check for the condition
i < 5. - As the condition evaluates to
true, it enters the loop body and adds the value ofitosumby executingsum += istatement. - As soon as the last statement ends, the control goes to the
final-expressioni.e.i++which incrementsiby1. - After this, the condition is checked again with the updated value of
iand the loop keeps on executing until the condition evaluates tofalse. - In the last iteration, the value of
iwould be5. This would fail the conditioni < 5and 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.
whileloop
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 aninitializationstep just as inforloop. - We run the
whileloop until the value ofiis less than5. The conditioni < 5can be seen as theconditionexpression like inforloop. - We define the
final-statementi.e.i++which must be executed so that the loop variable changes and condition evaluates tofalseat 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
falseand the loop will be executed infinitely.
do...whileloop
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)