Loops in JavaScript
Loops can execute a block of code a number of times
JavaScript For Loop
- For Loops can execute a block of code a number of times.
- For Loops are fundamental for tasks like performing an action multiple times.
The for statement creates a loop with 3 optional expressions:
for (exp 1; exp 2; exp 3) {
// code block to be executed
}
exp 1 is executed (one time) before the execution of the code block.
exp 2 defines the condition for executing the code block.
exp 3 is executed (every time) after the code block has been executed.
From the example above, you can read:
- exp 1 sets a variable before the loop starts (let i = 0).
- exp 2 defines the condition for the loop to run (i must be less than 5).
- exp 3 increases a value (i++) after the code block has been executed.
How to use exp 1
exp 1 is used to initialize the variable(s) used in the loop (let i = 0).
exp 1 is optional.
You can omit exp 1 if the value is set before the loop starts
How to use exp 2
exp 2 is used to evaluate the condition of the initial variable (i < len).
exp 2 is also optional.
If exp 2 returns false, the loop will end.
How to use exp 3
exp 3 increments the value of the initial variable (i++).
exp 3 is optional.
exp 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.
exp 3 can be omitted (if you increment the value inside the loop):
Loop Scope
Using var in a loop:
Using let in a loop:
In the first example, using var, the variable declared in the loop redeclares the variable outside the loop.
In the second example, using let, the variable declared in the loop does not redeclare the variable outside the loop.
When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.
JavaScript While Loops
While loops execute a block of code as long as a specified condition is true.
JavaScript have two types of while loops:
- The while loop
- The do while loop
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
The do while runs at least once, even if the condition is false from the start.This is because the code block is executed before the condition is tested.
Comparing For and While
A while loop is much the same as a for loop, with statement 1 and statement 3 omitted.
note:
- If you forget to increase the variable used in the condition, the loop will never end.
- This will crash your browser.
Reference :












Top comments (0)