Loops in JavaScript
Learn via video course
Overview
A loop is a statement that enables the programmer to execute the same block of code repeatedly. The purpose of loops is to automate repetitive tasks to save time and effort.
Loops in JavaScript are of two main types: entry-controlled loops and exit-controlled loops. Loops like the for loop and the while loop are entry-controlled loops, while the do-while loop is an exit-controlled loop. There are various statements like the break and continue statements that help regulate the control of flow in a loop.
Introduction
Programming is undoubtedly a lot of fun if you can relate it to real-life instances. Let us suppose that you have to prepare a cheese sandwich. Here are the steps you'd follow once you have all the ingredients:
- Take two slices of bread
- Put a slice of cheese on one slice of bread
- Sandwich the cheese between both the bread slices
- Put the sandwich in the griller
- Serve hot
What if you have to serve these sandwiches to a large family of 20 members wherein each person would eat two sandwiches? This would be quite a redundant and tedious process.
What if you asked a computerized machine to create those sandwiches?
Would it make your work easy?
It would be a lot more complicated. You would have to write code for the aforementioned lines of instruction over 40 times to achieve the desired result.
These combined would be nearly 200 lines of code for such a simple task! This would be extremely time-consuming and would render the code increasingly difficult to debug as well.
Fortunately enough, there is a way to dictate the computer to repeat an action without having to repeat the code. These flow-control commands are known as loops.
Categories of Loops
Loops are instructions passed on to machines to perform repetitive tasks.
There are two broad categories of loops based on the positioning of the flow-control systems: entry-controlled loops and exit-controlled loops.
Entry-controlled loops
An entry-controlled loop first checks if the conditions at the time of entry into the loop are met. If the condition is satisfied, then control is transferred into the body of the loop. If the condition is not met, the loop is not executed.
It can be considered to be like a security guard that authenticates your identity and frisks you before you enter a building. In the structure, a loop asks a question. If the question receives an answer, it is executed. If not, execution is terminated. Each act of questioning is known as an iteration.
Valid examples of entry-controlled loops could be for loops in JavaScript and while loops.
Exit-controlled Loops
An exit-controlled loop is a loop in which the condition is evaluated after the execution of the loop's body. Even if the condition is not satisfied, the loop has already been executed once. In simpler words, an exit-controlled loop controls the exit points of the loop. An exit-controlled loop would be like a security staff that frisks passengers after they have already passed through the entrance of the airport.
Exit-controlled loops are used when test conditions need to be checked after the execution of the loop. A do-while loop is a perfect example of an exit-controlled loop.
Basic Syntaxes
The basic syntax for an entry-controlled loop.
The basic syntax for an exit-controlled loop.
Types of Loops in JavaScript
We now know that loops in JavaScript are flow-control statements desiring to bring about automation in repetitive tasks within a program to save time and effort.
We shall now be carefully observing each loop in JavaScript.
For loops in JavaScript
For loops in JavaScript are one of the most commonly used loop constructs.
A for loop is an entry-controlled loop that repeats a block of code if the specified condition is met. A for loop in JavaScriptis typically used to loop through a block of code multiple times.
Syntax
- The initializing statement initializes the concerned counter variable. Any order of complexity is accepted here.
- The conditional statement checks whether the required condition is satisfied or not at the beginning of each iteration. If the value of the conditional statement is true in the for loop, the statement executes. If the conditional statement is false, the for loop terminates. If there is no conditional statement provided, the for loop is executed anyway.
- The update statement increases or decreases the loop counter each time it is executed.
Example of For Loops in JavaScript
Let us write a simple program to print the numbers 1 to 10 in JavaScript using for loops.
While loops in JavaScript
A while loop executes the respective statements as long as the conditions are met. As soon as the condition becomes false, the loop is terminated, and the control is passed on to the statement outside the loop. It is important to note that while is an entry-controlled loop in JavaScript. This means that, like other entry-controlled loops, the conditional statement first needs to be evaluated. If the conditions are met, only then is the counter variable updated.
Here is the basic syntax of a while loop
Example of while loops in JavaScript
Let us print the numbers 1 to 10 using the while loop in JavaScript.
Infinite Loops
An infinite loop is a loop that never becomes false. They are desirable in cases wherein the server has to run incessantly. However, infinite loops are often undesirable and they may tend to crash the browser.
The aforementioned code results in an infinite loop. This is because the value of the counter variable 'i' is decreasing every time after being printed. So, it satisfies the conditional (i<=10) again and again, resulting in an infinite sequence.
Do...while loops in JavaScript
A do...while loop is an exit-controlled loop. This means that the do...while loop executes the block of code once without checking the condition. After the code has been executed once, the condition is checked. If the condition is true, the code is executed further. If the condition is false, the loop is terminated.
The do...while statement is used when you want to run a loop at least one time.
Here is the basic syntax for a typical do...while loop.
Example of Do...while loops in JavaScript
Let us write a simple code in JavaScript to print numbers from 1 to 10.
Break and Continue Statements
A break is a general term in modern English for a respite or a long halt from something.
A break statement in JavaScript pauses or terminates the loop is executed. It is the best way to exit a loop early and avoid running the risks associated with infinite loops.
It is used to terminate statements. For example:
In the above code, the loop would break as soon as the value of the counter variable 'i' would become equal to 3.
A continue statement is used to terminate an existing iteration before the loop ends and proceeds to the next iteration.
Here is an example:
Label Statements
Labels are one of JavaScript's lesser-known features. They help users affix labels to the code for better readability and to name blocks of code. Labels help to make the code easier to understand by properly demarcating the different sections of the code.
Labels allow one to break and continue labeled statements.
Here is the basic syntax for labels in JavaScript
Example of Label Statements
For...in Statements
A for...in the statement is used to iterate over those properties of objects that have been keyed. We can say in crude terms that they have been 'indexed.' This means that each time the loop iterates, a key is assigned to a variable named key. This key is used to display the properties of the object it is linked to. This is like a for loop, but it only iterates over enumerable properties keyed by strings or arrays.
Here is the basic syntax for a for...in statement:
Example of for...in in JavaScript
The aforementioned code is used to print the details of the patient Isabel by viewing her health record. The for...in statement iterates over the object patient and displays the records in it. The object key is assigned the variable 'key'. The value of the key could be accessed by the patient[key]
For...of Statement in JavaScript
A for...of statement is like a counterpart of the for...in statement. Except iterating through the properties of the enumerable object, it loops through its values.
Here is the basic syntax for a for...of statement
Example of for...of in JavaScript
The aforementioned code is used to print the patients linked to a hospital's health records. Here, patients is the iterable object (array, in our case). Element is an item in the iterable object. For every element in the iterable object 'patients', the body of the loop is executed.
For-await-of statement
The for-await-of statement is used to create loops that iterate over async and sync objects like arrays, map-sets, etc. It can be used only inside an async function. It can trigger custom iteration workflows for each property of the object.
Here is the syntax for the statement:
for await (variable of iterable) { statement }
Example of for-await-of statement in JavaScript
The aforementioned code is used to print 'apple' and 'mango'. On each iteration, a newer value is assigned to the variable x. All the values of the iterable object(the array, in this case) are printed.
Difference Between while and do-while Loops
While and do-while may sound very similar but have diverse functionalities.
while | do-while |
---|---|
It is an entry-controlled loop | It is an exit-controlled loop |
The conditional is checked first and then executed. | Statement is executed once first, and then the conditional is checked. |
Braces are not required in single statements. | Braces are required even in single sentences. |
Variable must be initialized before execution of the loop | Variable may be initialized within the loop also. |
Conclusion
- Loops are instructions passed on to machines to perform repetitive tasks. This article shall delve into:
- An entry-controlled loop checks the conditions before the execution of the loop.
- Examples are for loops and while loops.
- An exit-controlled loop executes the loop before checking the conditional.
- Examples are do-while loops.
- A label is used to label particular code blocks.
- A for...in the loop is used to iterate through specific object properties.
- A for...in the loop is used to iterate through specific object values.
- The for-await-of statement is used to create loops that iterate over async and sync objects.