4QL4
4QL4
FOURTH QUARTER
L L
E E
S S
S S
O O
N N
4 4
LOOPS
What is a Loop?
There are times when you want a block of code repeated over and over again
until a certain condition is satisfied. This can be done by creating a loop. A
loop is a repetitive cycle of a block of code until the condition is met.
In JS, there are a variety of loops:
1. For loop – it loops through a block of code within a specified number of
times.
2. While loop – It loops through a block of code until the condition is
satisfied.
3. Do-while loop – It is like while loop; however, it will execute the set of
codes at least one.
4. For-in loop – It loops through the elements of an array.
LOOPS
Note:
If for instance, you want to exit from the loop after a condition
has been met, you can use the break statement. This
statement will immediately break the loop and continue the
execution of codes after the said loop. The continue statement
will break the current loop and will continue to the next value.
For Loop
The for loop is used when you know how many times the block
of code must be iterated.
Syntax:
Sample Script
Browser
Output
Do this
While Loop
The while loop is used if you know when the condition will be
met. It will loop through the set of codes until the condition is
met.
Syntax:
Sample Script
Browser
Output
Do this
Do-While Loop
Do-while loops work like the while loop except that the code
will be executed once and is repeated as long as the set
condition is true, but will stop once the condition is false.
Syntax:
Sample Script
Browser
Output
Do this
For-in Loop
For-in loop through the elements of an array or an object.
Syntax:
Sample Script
Browser
Output
Do this
Break and Continue statements
The break statement will stop or break the loop once the
specified condition becomes true and then execute the next
code if any after the loop.
Sample Script
Browser
Output
Continue statement
The continue statement will stop or break the loop for a set
value then continue to loop with the nest value.
Sample Script
Browser
Output