0% found this document useful (0 votes)
6 views

Lecture 3 - Loops and Strings2

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 3 - Loops and Strings2

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

What are Loops in JavaScript?

Loops in JavaScript are a way to write or repeat a block of code multiple times.
We use them when we want to run the same code again and again, but with
different values or conditions.

Here’s a breakdown of how the for-loop code works, along with a detailed
explanation:

Example Using a For Loop


for (let i = 1; i <= 5; i++) {
console.log("This is loop number: " + i);
}
How the Code Works
1. Initialization:
o let i = 1; It happens only once
o The loop starts by setting the variable i to 1. This is the starting point.
2. Condition Check:
o i <= 5; The stopping condition is checked repeatedly before each
loop.
o Before each loop, it checks if i is less than or equal to 5. If true, it
continues; if false, it stops.
3. Code Block:
o console.log("This is loop number: " + i); Print until the condition is
true or value ≤ 5.
o If the condition is true, it runs this code, printing: "This is loop number:
" + i.
4. Increment:
o i++; i++ adds 1 to i after each loop runs.
o After running the code block, i is increased by 1 (from 1 to 2, then 2 to
3, and so on).
5. Repeat:
o Steps 2-4 repeat until i is no longer less than or equal to 5.
Summary of Output:
 The output will be:
This is loop number: 1
This is loop number: 2
This is loop number: 3
This is loop number: 4
This is loop number: 5

Conclusion:
 This loop runs 5 times, printing the current value of i each time. The loop
starts at 1 and stops after printing when i reaches 5. This demonstrates how
a loop can repeat a block of code with changing values.

Why Do We Use Loops?


We use loops to avoid writing repetitive code. For example, if you want to print
numbers from 1 to 5, instead of writing 5 console.log statements, you can use a
loop to do it in just a few lines.
Here's an example to explain why we use loops in JavaScript:
Without using a loop:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
In this case, we are manually writing console.log five times to print numbers from
1 to 5.
With a loop:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Explanation:
 Without a loop, you have to repeat the same console.log statement for
each number.
 With a loop, you write the console.log once, and the loop runs it 5 times,
saving time and effort.
Output:
1
2
3
4
5
This shows how loops help avoid repetitive code by handling tasks in fewer lines.

Types of Loops in JavaScript:


There are 5 main types of loops in JavaScript:
General Loops:
1. for Loop (Is used when we know the stopping condition beforehand)
2. while Loop (Is used when we don’t know the stopping condition
beforehand)
3. do...while Loop (Is used when we want to run the code at least once, no
matter what.)
Special Loops:
4. for...in Loops
5. for...of Loops
1. for Loop
 When to use: When you know the stopping condition like how many times
you want to repeat or print something.
 How it works: It runs the code a specific number of times.
Example 1:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
This will print numbers from 1 to 5.
___________________________________________________________________________________
_______
Example 2:
Sum of numbers from 1 to n using for loop.
Code
let sum = 0; // Initialize sum to 0
let n = 100; // Define the maximum value for n

for (let i = 1; i <= n; i++) { // Loop from 1 to n (100 in this case)


sum += i; // Add each number to the sum
}
// Print the result
console.log("Sum of numbers from 1 to " + n + " is: " + sum);
console.log("Loop has ended.");
Explanation:
1. Variable Initialization:
let sum = 0;
let n = 100;
o sum is initialized to 0, which will store the cumulative total.
o n = 100 defines the range (1 to 100) over which the loop will run.
2. Loop:
for (let i = 1; i <= n; i++) {
sum += i;
}
o The loop starts from i = 1 and runs until i <= 100.
o sum += i means that with each iteration, the value of i is added to
sum. This operation accumulates the total sum.
3. Output:
console.log("Sum of numbers from 1 to " + n + " is: " + sum); // Output: 5050
console.log("Loop has ended."); // Output: Loop has ended.
o After the loop finishes, the total sum is printed.
o A message indicates that the loop has ended.

2. while Loop
 When to use: When you don’t know how many times the loop should run,
but you have a condition.
 How it works: It runs as long as the condition is true.
Example:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
This also prints numbers from 1 to 5, but the condition checks before each loop.

Example: User Input with a while Loop - Adding Numbers Until a Specific
Input that is (0) here.

let number;
let sum = 0;
while (number !== 0) {
number = parseInt(prompt("Enter a number (0 to stop):"));
sum += number; // Add the entered number to the sum
}
console.log("The total sum is: " + sum);
Explanation:
 Initialization: number starts as undefined, and sum is initialized to 0.
 Condition: The loop continues as long as number is not 0.
 Inside the Loop:
o The user is prompted to enter a number.
o The entered number is converted to an integer and added to sum.
 Exit: When the user enters 0, the loop stops, and the total sum is displayed.
Example Interaction:
1. User is prompted: "Enter a number (0 to stop):"
2. User enters: 5
o Output: (not visible, but it adds 5 to sum)
3. User is prompted again: "Enter a number (0 to stop):"
4. User enters: 3
o Output: (not visible, but it adds 3 to sum)
5. User is prompted again: "Enter a number (0 to stop):"
6. User enters: 0
o The loop stops.
Final Output:
After entering 0, the output in the console will be:
The total sum is: 8

Notes:
 The sum (8) is the result of adding all the numbers entered before the user
typed 0.
 This example is easy to understand, and the output clearly shows the total
of the entered numbers.
Can we write the prompt outside of the loop?
let number; // Declare the variable first
let sum = 0; // Initialize sum to 0
while (number !== 0) {
number = parseInt(prompt("Enter a number (0 to stop):")); // Get the number
inside the loop
sum += number; // Add the entered number to the sum
}
console.log("The total sum is: " + sum); // Output the total sum
Advantages of Writing Prompt inside loop;
1. Clearer Flow: You ask for the number right at the start of each loop
iteration. This makes it easier to understand how the program works.
2. No Infinite Loop Risk: Since you're prompting for the number every time
in the loop, you avoid the risk of getting stuck if the initial value is never
updated.
3. Fewer Lines of Code: It’s more concise because you only need to prompt
once per iteration.
Summary
This version is the simplest and most recommended approach because it
clearly shows the logic and avoids potential issues with uninitialized variables.
Great job!

3. do...while Loop
 When to use: When you want to run the code at least once, no matter
what.
 How it works: It runs the code first, then checks the condition.

Example:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
This runs at least once, even if the condition is false.

for loop example:


// The loop will run exactly 10 times
for (let i = 1; i <= 10; i++) {
console.log(i); // Prints numbers 1 to 10
}
 Comment: The for loop is used when you know the loop will run 10 times
(fixed).
While loop example:
let guess; // Variable to store user input
while (guess !== 5) { // The loop keeps running until the user guesses
the correct nbr (5)
guess = prompt("Guess the number"); // Keeps asking until correct
}
 Comment: The while loop keeps running, and the number of iterations is
unknown until the correct number 5 is guessed.
Summary:
 for: Runs a set number of times.
 while: Runs until a condition is met.
Key point:
The loop will keep running until the user guesses 5.

1. for...in Loop
Definition:
The for...in loop is used to iterate over the properties (keys) of an object or the
indices of an array.
When to Use:
 Use it when you want to loop through the keys of an object or the indices
of an array.
Example:
let person = {
name: "Alice",
age: 25,
city: "New York"
};
// Using for...in to loop through object properties
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output:
name: Alice
age: 25
city: New York
2. for...of Loop
Definition:
The for...of loop is used to iterate over iterable objects, like arrays, strings, or
other collections. It provides the values directly. It lets you get each item one by
one.
When to Use:
 Use it when you want to loop through the values of an iterable, such as the
elements in an array.
Example:
If you have a list of fruits:
let fruits = ["apple", "banana", "cherry"];
You can use for...of to print each fruit:
// Using for...of to loop through array elements
for (let fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
cherry

Key Point:
 for...of is simple and helps you work with the actual items in a collection
without needing to know their positions (indexes).
Key Differences
Feature for...in for...of
Iterates Loops through the keys of an It oops through the values of
over object or the indices of an an array or other iterable
array. objects.
Best For Use when you want to access Use when you want to access
the property names in an the actual items in an array
object or the position in an or string.
array.
Output K Returns keys (like "name" or Returns values (like "apple"
index 0). or "banana").
Conclusion
 Use for...in when you need to access the keys of an object or indices of an
array.
 Use for...of when you want to work with the actual values in an iterable
object.

Conclusion
Loops make our code more efficient by avoiding repetition. Choosing the right loop
depends on your needs: whether you know how many times the loop should run
or not, and whether you're working with arrays or objects.

You might also like