Lecture 3 - Loops and Strings
Lecture 3 - Loops and Strings
General Loops:
1. for loop: Repeats block of code a specific number of times.
Use Case: Best when you know the exact number of iterations needed beforehand.
Example 1:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Note: (i has a block scop with let keyword and global scope with var).
Explanation:
o This loop will print the numbers 1 to 5 in the console.
o The loop starts at i = 1
o It runs while i <= 5.
o Each time, i increases by 1 (i++).
Summary: The loop starts with i set to 1, which happens only once. The
stopping condition is checked before each round; the loop continues to run as long
as i is 5 or less. Each time the loop runs, i increases by 1. The loop stops when
the stopping condition is met, which is when i becomes greater than 5 means
5 + i++ = 6 than it will come out of the loop.
size++: This is the increment operator, which adds 1 to size. It's shorthand for size =
size + 1. We can add maximum value 1 to the size using size++ we cannot add
value more than 1..
size += 1: This is another way to add 1 to size, doing exactly the same as size++.
But we can add 1 or more than 1 to the size.
In your context, both will give the same result, so you can use either. It's just a matter of
preference or style.
Infinite loop:
A loop that never ends means the stopping condition always true.
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 count = 0;
while (count < 5) {
console.log(count);
count++;
}
Explanation:
o This loop will print the numbers from 0 to 4.
o The loop continues as long as count < 5.
o count increases by 1 with each iteration.
Use Case: Useful when the number of iterations is not predetermined and depends on
dynamic conditions.
Summary: In this example, the condition count < 5 is fixed, so we do know the loop will
run 5 times. However, in many real-world cases, the condition isn't fixed or known ahead of
time. For example, if the condition depends on user input or some changing value during
the program, then we don’t know how many times the loop will run. That's when a while
loop is useful.
Question:
Example of a while loop where the number of times the loop runs depends
on user input, and we don’t know how many times it will run in advance?
Answer:
Here’s an example where the loop keeps asking the user for input until they enter "exit".
We don’t know how many times the loop will run because it depends on when the user
types "exit".
Example:
let userInput = "";
while (userInput !== "exit") {
userInput = prompt("Type something (type 'exit' to stop):");
console.log("You entered: " + userInput);
}
What happens here:
The loop starts, and the condition is userInput !== "exit".
The program asks the user to type something.
As long as the user doesn’t type "exit", the loop will keep running and printing what
they entered.
When the user types "exit", the loop stops.
Why it's different:
Here, the loop could run 2 times, 10 times, or 100 times — we don't know in
advance. It entirely depends on when the user decides to type "exit".
Question 2:
Can you give an example of a while loop where the number of times the loop runs
depends on numerical user input, and we don’t know how many times it will run in
advance?
Answer:
Here’s an example where the loop keeps asking the user to enter a number. The loop
stops when the user enters a number greater than or equal to 100. We don’t know
how many times the loop will run because it depends on what numbers the user
enters.
Example:
let userNumber = 0;
while (userNumber < 100) {
userNumber = parseInt(prompt("Enter a number (100 or more to stop):"));
console.log("You entered: " + userNumber);
}
What happens here:
The loop starts with userNumber set to 0.
The condition is userNumber < 100, so the loop will keep running until the user
enters a number 100 or greater.
Each time, the program asks the user to enter a number, converts it to a number
with parseInt, and prints what they entered.
The loop stops when the user enters 100 or more.
Why it's different:
The loop could run 1 time, 5 times, or many times — it depends on what numbers the
user enters. So, we don’t know exactly how many times the loop will run in advance.
If the user types "42", the string "42" will be converted to the number 42.
Without parseInt, JavaScript would treat the input as a string, which could cause problems
when performing calculations or comparisons.
Can we use Number() instead of parseInt() to convert the user input
to a number?
Yes, we can use Number() instead of parseInt() to convert the user input to a number.
Here's how it would look:
let userNumber = 0;
while (userNumber < 100) {
userNumber = Number(prompt("Enter a number (100 or more to stop):"));
console.log("You entered: " + userNumber);
}
Difference between Number() and parseInt():
Number() converts the entire input into a number (including decimals). If the user
enters "42.5", it converts it to 42.5 (a floating-point number).
A floating-point number is a number that has a decimal point, like 5.0 or 42.5. It
can represent both whole numbers and fractions.
parseInt() only converts the whole number part of the input. If the user enters
"42.5", it converts it to 42 (an integer).
An integer is a whole number without any decimal or floating- point, like 5, 0, or -42.
It can be positive, negative, or zero.
For example, 5 is an integer, but 5.0 is a floating-point number.
So, if you expect decimal numbers, use Number(). If you only want whole numbers,
parseInt() might be more appropriate.
do...while loop: Executes the loop body at least once before checking the condition.
When to use: This runs the code at least once, even if the condition is false.
How it works: It runs the code first, then checks the condition.
Example:
let count = 0;
do {
console.log(count);
count++;
} while (count < 5);
Explanation:
This loop will print the numbers from 0 to 4.
The loop body executes once before checking count < 5.
count increases by 1 in each iteration.
Use Case: When you need to ensure that the loop body runs at least once, regardless of
the condition.
A do-while loop is another type of loop in programming. Here's why you might use it
instead of a for loop or a while loop:
Key Features of a Do-While Loop:
1. Guaranteed Execution:
o The code inside a do-while loop always runs at least once, even if the
condition is false. This is because the condition is checked after the code block
has executed.
2. Syntax:
o The structure looks like this:
do {
// Code to execute
} while (condition);
When to Use a Do-While Loop:
When you need to ensure that the loop runs at least once, such as when prompting
a user for input, and you want to validate that input after the first attempt.
Example:
let userNumber;
do {
userNumber = Number(prompt("Enter a number (greater than 10 to stop):"));
console.log("You entered: " + userNumber);
} while (userNumber <= 10);
Summary:
Use a do-while loop when you want to run the loop code at least once and then repeat it
based on a condition. It’s helpful for situations where the initial execution is needed before
checking the condition.
Special Loops
for...in loop: Iterates over the properties of an object and arrays.
A for-in loop is used to iterate over the keys (or property names) in an object. When we
use a for-in loop on an object, it returns each key one by one.
Use Case: Best for iterating over object properties when you need to access both keys and
values.
Example 1:
let student = { name: "Alice", age: 25, city: "Wonderland" };
In this example, the loop goes through the object student and prints each key: [ name,
age, and city].
So, a for-in loop does return the keys and their vales inside an object!
Example 2:
Explanation:
This code will iterate over each key in the person object.
The console.log(key + ': ' + person[key]); statement will print each key along with its
value in this format: key: value.
Expected Output:
name: Alice
age: 25
city: New York
3. for...of loop: Iterates over the values of an iterable object (like string and array).
Use Case: Ideal for working with strings and arrays and other iterable objects where
you need to access values directly.
Example 1:
Explanation:
This loop will print each fruit in the fruits array.
It directly iterates over the values of the array without needing to access them by
their indices.
Expected Output:
apple
banana
cherry
Everything looks good! Your explanation accurately describes how the for-of loop works.
Example 2:
Scenario A:
Scenario B:
Difference: In Scenario A, you see the size increase with each character, starting from 1.
In Scenario B, you see the size before it increases, starting from 0.
This structure provides a clear overview of each loop type along with their examples,
explanations, and use cases!
EXERCISE QUESTIONS
1. How can we print only odd and even numbers between 1 and 100 using a loop in
JavaScript?
Example
Example:
Explanation:
for (let i = 1; i <= 100; i++): This loop runs from 1 to 100.
if (i % 2 != 0): This condition checks if i is odd (not divisible by 2).
if (i % 2 == 0): This condition checks if i is even (divisible by 2).
Output (Odd Numbers):
1, 3, 5, 7, 9, 11, ..., 99
By using these simple loops, you can clearly separate odd and even numbers, making it
both easy to understand and visually structured.
EXERCISE QUESTIONS NO 2
Take a number input from the user, and if the entered number matches the pre-set correct
number, print 'Congratulations!' Otherwise, print 'Try again.
Example 2
Variable Naming: In JavaScript, it's best to avoid using Number as a variable name
since it can be confused with the built-in Number object. A better practice would be
to use a different name, like userNumber.
Type Checking: The prompt function always returns a string. If you're comparing
numbers (like 24), you should convert the input to a number using Number() to
ensure proper type comparison.
Key Explanation:
1. userNumber: A more suitable variable name.
2. Number(prompt(...)): Converts the input string to a number for accurate
comparison.
Example 2
Create a game where you start with a random game number. Ask the user to
keep guessing the game number until the user enters correct values?
let gameNumber = 25;
let userNumber = Number(prompt("Please enter the correct number here:")); // Get
user input and convert to number
Explanation:
1. Variable Initialization:
o let gameNumber = 25;: This sets the correct number that the user needs to
guess.
o let userNumber = Number(prompt(...));: Prompts the user for input and
converts it from a string to a number for accurate comparison.
Number(prompt(...));: This line does two things:
Prompts the User: It shows a message asking the user to enter a number.
Converts to a Number: It takes the input (which is in text form) and changes
it to a number. This is important because we need to compare numbers, not
text, to see if the user's guess is correct.
Example:
If the user types "25", prompt() gets it as a string ("25").
Number() converts that string into the number 25.
This way, we can accurately check if the user's guess matches the correct
number.
2. While Loop:
o while (userNumber !== gameNumber) { ... }: This loop continues to
prompt the user until they enter the correct number (25).
o Inside the loop, if the user does not enter the correct number, it prompts them
again for input.
3. Congratulatory Message:
o After the loop ends (meaning the user entered 25), it prints "Congratulations!
You entered the correct number.".
Strings in JavaScript
A string in JavaScript is a sequence of characters (like letters, numbers “24”, or
symbols) used to represent text. You can think of it as a word, sentence or a
paragraph that you can store and use in your code. For example:
"Hello, World!"
'JavaScript'
How to Create a String:
You can create a string by putting text inside single quotes (') or double quotes
("). Both work the same way.
let str1 = 'ApnaCollege';
let str2 = "ApnaCollege";
Built-in Properties and Methods in String:
Every string in JavaScript has built-in properties and methods:
Properties: These give information about the string. ( Character length
of word string is = 6 )
Methods: These allow you to change or manipulate the string. (abc to
ABC)
Summary
str.length tells you how many characters are in a string.
Indices let you access individual characters by their position.
These properties are easy to use and help you work with strings in
JavaScript!
In this example, the variables name and age are included in the string.
3. str.trim()
o This method removes any spaces only from the beginning and end of the
string.
Example:
let text = " Hello, World! ";
console.log(text.trim()); // Outputs: "Hello, World!"
4. str.slice(start, end?)
o This method extracts a part of the string from the start index to the end index
(not including the character at the end index).
Example:
let text = "JavaScript";
console.log(text.slice(0, 4)); // Outputs: Java
5. str1.concat(str2)
o This method combines two strings together.
Example:
let str1 = "Hello, ";
let str2 = "World!";
console.log(str1.concat(str2)); // Outputs: Hello, World!
6. str.replace(searchVal, newVal)
o This method replaces the first occurrence of searchVal in the string with
newVal.
Example:
let text = "I love apples.";
console.log(text.replace("apples", "bananas")); // Outputs: I love bananas.
7. str.charAt(idx)
o This method returns the character at the specified index idx.
Example:
let word = "JavaScript";
console.log(word.charAt(0)); // Outputs: J
Practice Exercise
Task: Ask the user to enter their full name. Create a username for them based on their
input.
Requirements:
The username should start with @, followed by the full name, and end with the total
number of characters in the full name.
Example:
If the user enters "shradhakhapra", the generated username should be
"@shradhakhapra13". (13 is the number of characters in the name).
Final Output
If the user enters their full name as shradhakhapra, the output will be:
Generated Username: @shradhakhapra13