Loops are used to repeatedly run the same piece of code as long as a predetermined condition is satisfied. A loop's main purpose is to save time and effort by automating the repetitive processes within a program.
The ability to execute a collection of instructions or functions repeatedly while a certain condition is true is known as looping in programming languages. Let's say we wish to print "Hello World" ten times, for instance.
- while: executes a block of code repeatedly so long as the given condition evaluates to true.
- do…while: executes a block of code once in a loop before evaluating the condition. The statement is repeated as long as the provided condition is true if the condition is true.
- for: cycles through a code block until the counter reaches a certain value.
- for…in: iterates over an object's attributes.
- for…of: loops through Iterable objects like strings, arrays, etc.
1. The while Loop
The general syntax is as follows:
2. The do...while Loop
A variation of the while loop that examines the condition at the conclusion of each loop iteration is the do-while loop. A do-while loop repeats a statement as long as the supplied condition evaluates to true after executing a block of code once and before determining if the condition is true.
3. The for Loop
As long as a specific condition is satisfied, the for loop repeats a section of code. It is often employed to run a code block a certain number of times.
The parameters of the for loop statement have following meanings:
- initialization: it sets the counter variables to their initial values and is evaluated once before the body of the loop is first executed.
- condition: this variable is assessed at the start of each iteration. The loop statements run if it evaluates to true. The loop will stop executing if it evaluates to false.
- increment: it adds a fresh value to the loop counter each time it executes.
4. The for...in Loop
The for-in loop is a particular kind of loop that iterates over an object's attributes or an array's items.
The for-in loop counter, or variable, is a string rather than a number. It includes the index of the current array element or the name of the current property.
5. The for...of Loop ES6
A new for-of loop introduced in ES6 makes it very simple to iterate over arrays and other iterable objects (like strings). Every member of the iterable object receives an execution of the code contained within the loop.