Lecture 3 - Loops and Strings2
Lecture 3 - Loops and Strings2
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:
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.
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.
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.