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

Lecture 3 - Loops and Strings

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lecture 3 - Loops and Strings

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER – 3

Loops and Strings in JavaScript?

What are loops in JS?


In JavaScript, Loops are used to execute a piece of code again and again until certain
condition is met.
They help avoid writing the same code over and over again.

Here are some common examples of loops;

1. Iterating through arrays:


Input: Loop through ["apple", "banana", "cherry"].
Output:
apple
banana
cherry
Iterating means going through each item in a list or collection one by one. In the example,
it involves accessing each fruit in the array ["apple", "banana", "cherry"] to perform an
action, like printing it.

2. Counting or summing numbers:


Input: Loop from 1 to 10, adding each number.
Output:
55
3. Creating a countdown:
Input: Loop from 5 to 1.
Output:
5
4
3
2
1
4. Generating a table of values:
Input: Loop from 1 to 5 for 2 x i.
Output:
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
5. Filtering data:
Input: Loop through [1, 2, 3, 4, 5, 6] to collect even numbers.
Output:
[2, 4, 6]
Common Types of Loops:
o General loops: These include for, while, and do-while loops. They all iterate or loop
in similar ways but with different structures. The way we set them up in the code is a
little different.
o Special loops: These include for-in and for-of loops. They are used to iterate or loop
through specific data types like objects or strings and arrays.

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++).

 Initiation: The loop starts with i = 1. which happens only once.


 Stopping Condition: The loop will keep running as long as i is 5 or less or I
<= 5. It checks the stopping condition to match the i for equal to or less than 5
before each round.
 Updation: Each time the loop runs, i increases by 1 (i++), repeating until i is
greater than 5.

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.

Example 2: Lets sum the numbers from 1 to 5 by using loop function;


The sum from 1 to 5:
let sum = 0; // Start with a sum of 0
for (let i = 1; i <= 5; i++) { // Loop from 1 to 5
sum += i; // Add the current number (i) to the sum
}
console.log(sum); // Show the total sum of 1 to 5 = 15
Explanation:
 Initialize the sum:
o let sum = 0;
This line sets the starting value of sum to 0. This is where we will add all the
numbers.
 Set up the loop:
o for (let i = 1; i <= 5; i++) {
This line creates a loop that starts with i at 1 and will continue as long as i is
less than or equal to 5. The i++ means that i will increase by 1 after each loop.
 How to adds i to the sum:
o sum += i;
Inside the loop, this line takes the current value of i and adds it to sum. For
example:
 When i is 1, sum becomes 0 + 1 = 1.
 When i is 2, sum becomes 1 + 2 = 3.
 When i is 3, sum becomes 3 + 3 = 6.
 When i is 4, sum becomes 6 + 4 = 10.
 When i is 5, sum becomes 10 + 5 = 15.
 Print the total:
o console.log(sum);
After the loop finishes (when i exceeds 5), this line displays the final value of
sum, which is 15.
Result:
The total sum of numbers from 1 to 5 is 15.

Logical Difference Between ( i++ and i += 1 )?


There is a logical difference between size++ and size += 1 in our case. Both are doing the
same thing: increasing the value of size by 1. But here is a catch:

 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.

Why we use parseInt?


ParseInt is a function in JavaScript that converts a string into an integer (whole
number).

Why do we use it?


When you get input from the user using prompt(), it is always in the form of a string (even
if they type a number). If you need to work with this input as a number (like for math or
comparisons), you must convert it to a number.

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" };

for (let key in student) {


console.log(key); // This will print "name", "age", and "city"
}

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:

const person = { name: 'Alice', age: 25, city: 'New York' };

for (let key in person) {


console.log(key + ': ' + person[key]);
}

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

So, with the closing brace added, your code is correct!

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:

let fruits = ['apple', 'banana', 'cherry'];

for (let fruit of fruits) {


console.log(fruit);
}

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.

Does the position of the print statement matter? Is it okay to write


the console.log() statement inside the loop before or after increment
size which is i++?
When you use console.log() before and after size++, you will see each character printed
two times in the output:
1. Before size increases: The first console.log(val, size); shows the character with the
current value of size, which starts at 0 and goes up to 10.
2. After size increases: The second console.log(val, size); shows the same character
but with the new value of size, which will be from 1 to 11.
So, for each character, you will see two lines:
 The first line shows the character and the size before it increases.
 The second line shows the character and the size after it increases.
This means you'll see each character printed twice with different values of size.

Example 2:
Scenario A:

let str = "apnacollege";


let size = 0;

for (let val of str) {


size += 1;
console.log(val, size);
}
 Outcome: This will print each character of str along with size starting from 1 up to
11. You will see the size increase with each character printed.

Scenario B:

let str = "apnacollege";


let size = 0;

for (let val of str) {


console.log(val, size);
size += 1;
}
 Outcome: This will print each character of str along with size starting from 0 and
going up to 10. In this case, size is shown before it increases for the character.

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?

1. Printing Odd Numbers (1 to 100)


You can use a loop to print only the odd numbers by checking if the number is not divisible
by 2 (i.e., number % 2 != 0).

Example

// Print odd numbers from 1 to 100


for (let i = 1; i <= 100; i++) {
if (i % 2 != 0) {
console.log(i);
}
}

2. Printing Even Numbers (1 to 100)


To print even numbers, you can check if the number is divisible by 2 (i.e., number % 2 ==
0).

Example:

// Print even numbers from 1 to 100


for (let i = 1; i <= 100; i++) {
if (i % 2 == 0) {
console.log(i);
}
}

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

Output (Even Numbers):


2, 4, 6, 8, 10, 12, ..., 100

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.

let userNumber = Number(prompt("Please enter Game Number here!.."));

if (userNumber === 24) {


console.log("Congratulations! You entered the correct number.");
} else {
console.log("Try again, please.");
}

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

// Loop until the user enters the correct number

while (userNumber !== gameNumber) {


userNumber = Number(prompt("Please enter the correct number here:")); // Get user
input again
}

console.log("Congratulations! You entered the correct number.");

// Once the correct number is entered, print a congratulatory message

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)

Important Built-in String Properties


1. length Property - str.length
 The .length property tells you how many characters are in the string,
including letters, numbers, spaces, and punctuation.
Example:
let text = "Hello, World!";
console.log(text.length); // Outputs: 13
In this example, "Hello, World!" has 13 characters.

2. String Indices – str[0];


 Each character in a string has a position number called an index. The first
character has index 0, the second has index 1, and so on. You can access
characters using these indices.
Example:
let word = "JavaScript";
console.log(word[0]); // Outputs: J
console.log(word[4]); // Outputs: S
o The character at index 0 is "J".
o The character at index 4 is "S".

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!

Template Literals in JavaScript – ( ` `)


Template literals are a special way to create strings in JavaScript. They allow you
to include variables and expressions easily within the string. Template literals use
backticks (`) instead of single or double quotes.
Key Features:
 Multi-line Strings: You can write strings that span multiple lines.
 Variable Insertion: You can insert variables and expressions directly into
string using ${ }.
Example of a Template Literal:

let name = "Alice";


let age = 25;

// Using a template literal


let greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting); // Outputs: Hello, my name is Alice and I am 25 years
old.

In this example, the variables name and age are included in the string.

Summary of Template Literals:


 Use backticks (`) to create a template literal.
 Easily insert variables and expressions with ${ }.
 Write multi-line strings without needing special characters.

Template literals make it simple to create dynamic and complex strings in


JavaScript!

String Methods in JavaScript


String methods are built-in actions you can perform on strings. Here are some important
string methods:
1. str.toUpperCase()
o This method converts all the characters in the string to uppercase letters.
Example:
let text = "hello";
console.log(text.toUpperCase()); // Outputs: HELLO
2. str.toLowerCase()
o This method converts all the characters in the string to lowercase letters.
Example:
let text = "HELLO";
console.log(text.toLowerCase()); // Outputs: hello

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

Summary of String Methods:


 toUpperCase(): Converts string to uppercase.
 toLowerCase(): Converts string to lowercase.
 trim(): Removes spaces from the start and end only.
 slice(start, end?): Extracts a part of the string.
 concat(str2): Combines two strings.
 replace(searchVal, newVal): Replaces a part of the string.
 charAt(idx): Gets the character at a specific index.
These methods help you manipulate and work with strings in JavaScript easily!

The difference between str[index] and str.charAt(index) is:


 str[index]: Directly accesses the character at the given position. It is newer and
preferred for simplicity.
 str.charAt(index): A method that returns the character at the specified position. It
is older and sometimes used for backward compatibility.
Both do the same thing but str[index] is more modern and cleaner to use.

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).

Practice Exercise Solution

Step 1: Prompt the User


Ask the user to enter their full name.
Step 2: Get the Full Name
Store the user input in a variable.
Example:
 User enters: shradhakhapra
Step 3: Calculate the Length
Find the length of the full name using the .length property.
 Length of "shradhakhapra": 13
Step 4: Generate the Username
Create the username by combining:
 @
 Full name
 Length of the full name
Formula:
username = "@" + fullName + fullName.length
Example:
For the input shradhakhapra, the generated username will be:
 Username: @shradhakhapra13

Final Output
If the user enters their full name as shradhakhapra, the output will be:
Generated Username: @shradhakhapra13

You might also like