There are times when we would want to perform a certain operation a certain number of times, like if we have a list of employees with their salaries and we have to calculate their income tax. Now the formula for getting the income tax is the same for all employees, so we can have a loop and execute the code statements with different inputs.
Similarly, for a use case like printing the mathematical table of a number like 2, we can simply have a loop in place to keep on multiplying the number with 1, 2, 3, 4, and so on till 10, incrementing the multiplication factor every time.
The number of times a group of statements is executed depends on a condition provided in the loop, or if we are using the
for loop to traverse an array, list, etc, then the loop executes until complete traversal.
The loop statements are executed until the condition becomes false. When the condition becomes false, the execution of loop stops.
In this tutorial, we will cover the first three loops and we will cover the other in the next tutorial.
for loop, which lets you iterate the statements for a fixed number of times.
for loop consists of three statements to work:
initialization: here, the loop counter is initialized with its initial value.
condition: here, the condition statement is provided which is checked each time with respect to the value of the counter to continue the iteration.
iteration: this statement lets you decide whether you want to increase or decrease the initial counter value also known as increment/decrement.
for Loop: Syntax
Following is the syntax for the
for(initialization; condition; iteration)
The idea here is to initialize a counter, set a condition until which the loop will run, and keep on incrementing or decrementing the counter so that after certain iteration the condition fails, and the loop exits. If the condition never fails, the loop will keep on executing infinitely.
for Loop: Example
Let's take an example to see how the loop works,
for…in loop. The for/in loop automatically iterates over the fields of an object and the loop stops when all the fields are iterated.
for(key in object)
// code statements
for...in Loop: Example
Let's take an example to see it in action,
for...of Loop: Syntax
for(variable of iterable)
for...of Loop: Example
Below is an example in which we will traverse an array using the for/of loop.
let abc = ['BMW','FERARI','VOLVO'];
for(y of abc)
In this tutorial, we explained