Loops
If you want to run the same code over and over again, each time with a different value.
JavaScript supports different kinds of loops :
- for - loops through a block of code a number of times
- while - loops through a block of code while a specified condition is true
- do/while - also loops through a block of code while a specified condition is true
- for/in - loops through the properties of an object
- for/of - loops through the values of an iterable object
for Loop
Syntax
Initialization
It is executed only one time before the execution of the code block.
Condition
If the condition is true then code block will execute else loop will terminate.
Increment/Decrement
It will execute every time after the code block has been executed.
Example :
This will give the following result -
while Loop
While loop executes a statement as long as the specified condition is true. The while loop works same as for loop which is used only when we already knew the number of iterations. Where as the ‘while’ loop is used only when the number of iteration are not exactly known.
Here, initialization will be done above the while loop and iteration will be written anywhere in the loop.
Syntax
Example :
do while Loop
This do while loop also executes block of code until the specified condition is true. But the difference in do while and while loop is that the condition will be checked after the first execution.
In this do while loop, block of code will be executed at least once even the condition is false.
Syntax
Example :
for in Loop
This loop iterates over object properties.
Syntax
variableA different property name is assigned to variable on each iteration.
objectObject whose properties are iterated over.
Example :
for of loop
This loop iterates over Array, array-like objects.
Syntax
variableOn each iteration a value of different property is assigned to variable.
iterableObject whose properties are iterated.
Example :