Lecture Notes Of Day 6
Loops in JavaScript
Objective:
Learn how to use loops to repeat
code in JavaScript. Loops help to execute a block of code multiple times based
on a condition.
Topics
Covered:
1. for loop
2. while
loop
3. do...while
loop
1.
Introduction to Loops
In JavaScript, a loop is used to
execute a block of code repeatedly based on a condition. This saves us from
writing the same code over and over again. There are three main types of loops
in JavaScript:
1. For loop
2. While
loop
3. Do...while
loop
Each loop has its unique way of
functioning, and they can be chosen based on the specific needs of the problem.
2. The for
Loop
The for loop is the most common
loop in JavaScript. It is generally used when the number of iterations is known
before starting the loop.
Syntax of
for loop:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
- Initialization: It
is executed once before the loop starts. Usually used to set a loop counter.
- Condition:
The loop continues as long as this condition is true. Once it becomes
false, the loop stops.
- Increment/Decrement: It
is executed after each iteration and usually updates the loop counter.
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // Prints numbers 0 to 4
}
Explanation:
- The
loop starts with i = 0.
- The
condition i < 5 is checked. Since it's true, the loop body is executed,
and i is printed.
- After
each iteration, i is incremented by 1.
- Once
i becomes 5, the condition i < 5 becomes false, and the loop stops.
Output:
0
1
2
3
4
Common
Uses of for loop:
- Iterating
through arrays
- Repeating
a task a specific number of times
- Counting
from one number to another
3. The while
Loop
The while loop is used when the
number of iterations is not known, and we want to repeat the loop until a
condition is met. It checks the condition before each iteration.
Syntax of
while loop:
while (condition) {
// Code to be executed
}
- Condition:
This condition is evaluated before each iteration. If the condition is
true, the code inside the loop will run. If false, the loop stops.
Example:
let i = 0;
while (i
< 5) {
console.log(i); // Prints numbers 0 to 4
i++; //
Increment the value of i
}
Explanation:
- The
loop runs as long as i < 5.
- On
each iteration, i is printed, and then i is incremented by 1.
- The
loop stops once i becomes 5.
Output:
0
1
2
3
4
Common
Uses of while loop:
- When
the number of iterations is unknown.
- Repeating
code until a certain condition is met.
4. The do...while
Loop
The do...while loop is similar to
the while loop, except that it checks the condition after the loop body
is executed. This means that the code inside the loop is executed at least
once, even if the condition is false initially.
Syntax of
do...while loop:
do {
// Code to be executed
} while
(condition);
- Code
block: Executes at least once before the condition
is checked.
- Condition:
After the first iteration, the condition is evaluated. If it's true, the
loop continues.
Example:
let i = 0;
do {
console.log(i); // Prints numbers 0 to 4
i++; //
Increment the value of i
} while
(i < 5);
Explanation:
- The
loop will execute at least once, regardless of the condition.
- In
this case, the loop will run until i reaches 5.
Output:
0
1
2
3
4
Common
Uses of do...while loop:
- When
you need the loop to execute at least once, even if the condition is
initially false.
- Situations
where a task must be completed first, then a condition is checked to
continue or stop.
5.
Comparison Between the Three Loops
|
Loop |
Condition
Check |
When
to Use |
|
for loop |
Before execution |
When you know how many times
the loop should run. |
|
while loop |
Before execution |
When the number of iterations
is unknown. |
|
do...while loop |
After execution |
When you want the loop to run
at least once. |
6. Nested
Loops
You can also use loops inside
other loops, which are called nested loops. This is useful when you need
to perform a set of repetitive tasks within another repetitive task, such as
iterating over a matrix or a 2D array.
Example
of Nested for loop:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(`i = ${i}, j = ${j}`);
}
}
Explanation:
- The
outer loop runs three times (with i taking values 0, 1, 2).
- For
each value of i, the inner loop runs three times (with j taking values 0,
1, 2).
- This
results in 9 total iterations.
Output:
i = 0, j = 0
i = 0, j
= 1
i = 0, j
= 2
i = 1, j
= 0
i = 1, j
= 1
i = 1, j
= 2
i = 2, j
= 0
i = 2, j
= 1
i = 2, j =
2
7.
Infinite Loops
An infinite loop occurs when the
loop’s condition never becomes false. This causes the loop to run indefinitely,
which can crash your program or freeze your browser.
Example
of Infinite Loop:
let i = 0;
while (true)
{
console.log(i);
i++;
}
Explanation:
- The
condition true will always evaluate to true, meaning the loop will never
stop.
- It
will keep printing the value of i until the program is manually stopped.
Important: Always
make sure the loop condition will eventually be false, or else you risk
creating an infinite loop.
8.
Conclusion
Loops are an essential part of
programming, and understanding how to use them correctly will allow you to
efficiently solve problems and handle repetitive tasks. JavaScript provides
three main types of loops:
- For
loop for when the number of iterations is known.
- While
loop for when the number of iterations is unknown.
- Do...while
loop for situations where the loop should run at
least once.
Choosing the right loop based on
your task can make your code cleaner and more efficient.
Summary
of Loops in JavaScript
- for
loop: Best when you know how many times you need
to repeat the code.
- while
loop: Best when you need to repeat something an
unknown number of times, as long as a condition is true.
- do...while
loop: Ensures the loop runs at least once before
checking the condition.
Assignments:
1. Write a for
loop that prints the even numbers between 0 and 20.
2. Write a while
loop that prints the numbers from 10 to 1 in descending order.
3. Write a do...while
loop that prints numbers from 1 to 10 and stops if the number is greater than
5.
4. Write a
nested for loop that prints the following pattern:
*
**
***
****
*****
Solutions:
1. For loop
for even numbers:
for (let i = 0; i <= 20; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
2. While
loop for descending numbers:
let i = 10;
while (i
>= 1) {
console.log(i);
i--;
}
3. Do...while
loop:
let i = 1;
do {
console.log(i);
i++;
} while
(i <= 10 && i <= 5);
4. Nested
for loop pattern:
for (let i = 1; i <= 5; i++) {
let pattern = '';
for (let j = 1; j <= i; j++) {
pattern += '*';
}
console.log(pattern);
}
This concludes the lecture on
Loops in JavaScript.
