JavaScript Control and Looping Statements
JavaScript Control and Looping Statements
CSE326
Internet Programming Laboratory
Lecture #11 Part 2
Dr. Navneet Kaur
2
Dr. Navneet Kaur, Lovely
Professional University
Outline
Control statements
Looping statements
Popup boxes
3
Dr. Navneet Kaur, Lovely
Professional University
Control statements
Write a program to check whether number is positive or not
<!DOCTYPE html>
<html>
<head>
<title>If Statement Example</title>
</head>
<body>
<h2>Check if a Number is Positive</h2>
<p id="result"></p>
<script>
let num = 10;
if (num > 0) {
[Link]("result").innerHTML = num + " is a
positive number.";
}
</script>
</body>
5
Dr. Navneet Kaur, Lovely Profession
al University
Question
Check age of user
If age is greater than 18 message should be displayed you
are eligible to vote
Else not eligible to vote
6
Dr. Navneet Kaur, Lovely
Professional University
Control statements
if-else Statement - The if...else statement executes a statement
if a specified condition is true. If the condition is false, another
statement in the optional else clause will be executed.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
7
Dr. Navneet Kaur, Lovely Profession
al University
Question
Show the version with if–else next (to check positive or
negative)
Solution 8
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<head>
<title>If-Else Example</title>
</head>
<body>
<h2>Check if a Number is Positive or Negative</h2>
<p id="result"></p>
<script>
let num = -8; // You can change this number
if (num > 0) {
// [Link]("result").innerHTML = num + " is a positive number.";
Alert(num+“ is a positive number ”);
} else {
// [Link]("result").innerHTML = num + " is a negative number.";
Alert(num+“ is a negative number ”);
}
</script>
</body>
</html>
9
Dr. Navneet Kaur, Lovely
Professional University
Control statements
if-else-if Statement - Note that there is no elseif syntax in
JavaScript. However, you can write it with a space between else
and if.
if (x > 50) {
/* do something */
} else if (x > 5) {
/* do something */
} else {
/* do something */
}
10
Dr. Navneet Kaur, Lovely Profession
al University
Question
Check if a Number is Positive, Negative, or Zero
Solution 11
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<head>
<title>If Else If Example</title>
</head>
<body>
<h2>Check if a Number is Positive, Negative, or Zero</h2>
<script>
let num = parseFloat(prompt("Enter a number:"));
if (num > 0) {
[Link]( num + " is a positive number.“);
}
else if (num < 0) {
[Link]( num + " is a Negative number.“); }
else {
[Link]( num + " is a zero.“); }
</script>
</body>
12
Dr. Navneet Kaur, Lovely
Professional University
Control statements
Switch Statement - The switch statement evaluates an expression, matching
the expression's value against a series of case clauses, and executes
statements after the first case clause with a matching value, until a break
statement is encountered.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
13
Dr. Navneet Kaur, Lovely Profession
al University
Question
Check Day of the Week using Switch Statement
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Solution
14
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html> case 5:
<head> dayName = "Thursday";
<title>Switch Statement Example</title>
break;
</head>
<body> case 6:
<h2>Day of the Week using Switch Statement</h2> dayName = "Friday";
<p id="result"></p>
break;
case 7:
<script>
dayName = "Saturday";
let day = prompt(“enter a number “);
break;
let dayName; default:
switch (day) {
dayName = "Invalid day number!"
case 1: }
dayName = "Sunday";
break;
case 2: [Link]("result").
dayName = "Monday"; innerHTML = "Day " + day + " is " +
break;
case 3:
dayName + ".";
dayName = "Tuesday"; </script>
break;
case 4:
dayName = "Wednesday"; </body>
15
Dr. Navneet Kaur, Lovely
Professional University
Looping statements
Loops offer a quick and easy way to do something
repeatedly.
for statement - A for loop repeats until a specified condition
evaluates to false.
for (initialization; condition; afterthought)
statement
while statement - A while statement executes its statements as
long as a specified condition evaluates to true.
while (condition) {
statement }
16
Dr. Navneet Kaur, Lovely Profession
al University
Question
Display Numbers from 1 to 10 using For Loop
Solution 17
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<head>
<title>For Loop Example</title>
</head>
<body>
<h2>Display Numbers from 1 to 10 using For Loop</h2>
<p id="result"></p>
<script>
let text = "";
for (let i = 1; i <= 10; i++) {
text += i + "<br>";
}
[Link]("result").innerHTML = text;
</script>
</body>
18
Dr. Navneet Kaur, Lovely Profession
al University
Question
Display Numbers from 1 to 5 using While Loop
Solution 19
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<head>
<title>While Loop Example</title>
</head>
<body>
<h2>Display Numbers from 1 to 5 using While Loop</h2>
<p id="result"></p>
<script>
let i = 1;
let text = "";
while (i <= 5) {
text += i + "<br>";
i++; // increase the value of i by 1
}
[Link]("result").innerHTML = text;
</script>
</body>
20
Dr. Navneet Kaur, Lovely Profession
al University
Question
Display sum of 1 to 10 numbers using for loop
21
Dr. Navneet Kaur, Lovely Profession
al University
Solution
<!DOCTYPE html>
<html>
<head>
<title>For Loop Example 3</title>
</head>
<body>
<h2>Sum of First 10 Natural Numbers</h2>
<script>
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
[Link]("The sum of numbers from 1 to 10 is: " + sum);
</script>
</body>
</html>
22
Dr. Navneet Kaur, Lovely Profession
al University
Question
Display Multiplication Table of 5 by using for loop
23
Dr. Navneet Kaur, Lovely Profession
al University
Solution
<!DOCTYPE html>
<html>
<head>
<title>For Loop Example 4</title>
</head>
<body>
<h2>Multiplication Table of 5</h2>
<script>
for (let i = 1; i <= 10; i++) {
[Link]("5 × " + i + " = " + (5 * i) + "<br>");
}
</script>
</body>
</html>
24
Dr. Navneet Kaur, Lovely
Professional University
Looping statements
do...while statement - The do...while statement repeats until a
specified condition evaluates to false.
do {
statement
}
while (condition);
Question
Display Numbers from 1 to 5 using Do While Loop
<h2>Display Numbers from 1 to 5 using Do While Loop</h2>
Solution
26
Dr. Navneet Kaur, Lovely Profession
<p id="result"></p> al University
<script>
let i = 1; // starting value
let text = "";
do {
text += i + "<br>";
i++; // increase by 1
} while (i <= 5);
[Link]("result").innerHTML = text;
</script>
</body>
</html>
27
Dr. Navneet Kaur, Lovely Profession
al University
Question
Create menu-based program (using do...while + switch)
where the user can choose to perform operations like
"1. Print numbers from 1 to N
"2. Find sum of numbers up to N
"3. Print multiplication table
"4. Exit"
Do while example menu based 28
<script>
let choice;
case 3:
do { let num = parseInt(prompt("Enter a number for its multiplication table:"));
// Show menu options let i3 = 1;
choice = parseInt(prompt( [Link]("<h3>Multiplication Table of " + num + ":</h3>");
do {
"Choose an option:\n" +
[Link](num + " × " + i3 + " = " + (num * i3) + "<br>");
"1. Print numbers from 1 to N\n" +
i3++;
"2. Find sum of numbers up to N\n" +
} while (i3 <= 10);
"3. Print multiplication table\n" +
break;
"4. Exit"
)); case 4:
switch (choice) { alert("Exiting the program. Goodbye!");
case 1: break;
let n1 = parseInt(prompt("Enter a number:"));
let i1 = 1; default:
[Link]("<h3>Numbers from 1 to " + n1 + ":</h3>"); alert("Invalid choice! Please enter 1, 2, 3, or 4.");
do { }
[Link](i1 + "<br>");
i1++; } while (choice !== 4);
} while (i1 <= n1); </script>
</body>
break;
</html>
case 2:
let n2 = parseInt(prompt("Enter a number:"));
let i2 = 1, sum = 0;
do {
sum += i2;
i2++;
} while (i2 <= n2);
[Link]("<h3>Sum of numbers from 1 to " + n2 + " is " + sum + ".</h3>");
break;
29
Dr. Navneet Kaur, Lovely
Professional University
Question
Using Continue Statement in For Loop to skip 1 number
while displaying 1 to 10
for(init; condition; update) {
//code
if(condition to continue) {
continue;
}
//code
}
Solution
31
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<head>
<title>Continue Statement Example</title>
</head>
<body>
<h2>Using Continue Statement in For Loop</h2>
<p id="result"></p>
<script>
let text = "";
for (let i = 1; i <= 10; i++) {
if (i === 5) {
continue;
}
text += i + "<br>";
}
[Link]("result").innerHTML = text;
</script>
</body>
32
Dr. Navneet Kaur, Lovely
Professional University
<p id="result"></p>
<script>
let i = 0;
let text = "";
// skip number 5
if (i === 5) {
continue; // go to next iteration
}
text += i + "<br>";
}
[Link]("result").innerHTML = text;
</script>
</body>
34
Dr. Navneet Kaur, Lovely Profession
al University
Question
Skip Even Numbers using While Loop
35
<script>
let i = 1;
while (i <= 10) {
if (i % 2 === 0) {
i++;
continue; // Skip even numbers
}
[Link](i + "<br>");
i++;
}
</script>
36
Dr. Navneet Kaur, Lovely
Professional University
<!DOCTYPE html>
<html>
<body>
<p id="result"></p>
<script>
let i = 1;
let text = "";
while (i <= 10) {
if (i === 6) {
break;
}
text += i + "<br>";
i++;
}
[Link]("result").innerHTML = text;
</script>
</body>
38
Dr. Navneet Kaur, Lovely
Professional University
Question
Using do while loop Stop the Loop When Number
Equals 4
39
Dr. Navneet Kaur, Lovely Profession
al University
Solution
<script>
let i = 1;
do {
if (i === 4) {
break; // Stop loop when i becomes 4
}
[Link]("Number is: " + i + "<br>");
i++;
} while (i <= 10);
Popup boxes
JavaScript provides built-in global functions to display popup
message boxes for different purposes.
alert():The alert() function displays a message to the user to
display some information to users. This alert box will have
the OK button to close the alert box.
confirm(message): Use the confirm() function to take the user's
confirmation before starting some task.
prompt(message, defaultValue): Use the prompt() function to
take the user's input to do further actions.
Example 41
Dr. Navneet Kaur, Lovely Profession
al University
<body>
<h2>Using JavaScript Popup Functions</h2>
<button onclick="showPopups()">Click Me</button>
<p id="result"></p>
<script>
function showPopups() {
alert("Welcome to JavaScript pop-up demo!");
let userConfirm = confirm("Do you want to continue?");
if (userConfirm) {
let name = prompt("Please enter your name:");
[Link]("result").innerHTML = "Hello,
" + name + "! Nice to meet you.";
} else {
[Link]("result").innerHTML = "You
canceled the operation.";
}
}
42
Dr. Navneet Kaur, Lovely Profession
al University
Question
Create an HTML + JavaScript program that:
Uses a prompt() to ask the user for their name and age.
Uses a confirm() box to ask the user:
“Do you want to see a personalized message?”
If the user clicks OK, show an alert() message like:
“Hello, John! You are 25 years old — that’s awesome!”
If the user clicks Cancel, show an alert() saying:
“Okay, maybe next time!”
43
Dr. Navneet Kaur, Lovely Profession
al University
Types of Functions
No Return Type and no Parameters
With return type and with parameters
Without return type and no parameters
With return type and with parameters
44
Dr. Navneet Kaur, Lovely Profession
al University
1. <!DOCTYPE html>
<html>
<body>
<script>
function showMessage() {
[Link]("Welcome to JavaScript Functions!<br>");
}
showMessage();
showMessage();
</script>
</body>
</html>
45
Dr. Navneet Kaur, Lovely Profession
al University
Question
Create a program using function to greet user
Take input from user
47
Dr. Navneet Kaur, Lovely Profession
al University
<h2>Enter your name to get a greeting:</h2>
<input type="text" id="username" placeholder="Enter your name">
<button onclick="getNameAndGreet()">Greet Me</button>
<p id="result"></p>
<script>
function greetUser(name) {
[Link]("result").innerHTML = "Hello, " + name + "!";
}
function getNameAndGreet() {
let user = [Link]("username").value;
if (user === "") {
[Link]("result").innerHTML = "Please enter your
name!";
} else {
greetUser(user); // passing parameter to function
}
}
</script>
48
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<body>
<script>
function addNumbers(a, b) {
return a + b;
}
let result = addNumbers(8, 12);
[Link]("Sum = " + result);
</script>
</body>
</html>
53
Dr. Navneet Kaur, Lovely Profession
al University
Question
Create Function with User Input (Arguments + Return) to
calculate Area of rectangle
Another example 54
Dr. Navneet Kaur, Lovely Profession
al University
<!DOCTYPE html>
<html>
<body>
<script>
function calculateArea(length, width) {
return length * width;
}
Question
Questions
Write a function average(x, y, z) that returns the average of
three numbers.
Write a function checkEvenOdd(num) that checks whether
the number is even or odd, and displays the result.
Write a function calculateSimpleInterest(p, r, t) that returns
Simple Interest = (p × r × t) / 100.
Write a function fahrenheitToCelsius(f) that converts
Fahrenheit temperature to Celsius using
C = (f - 32) * 5 / 9
58
Dr. Navneet Kaur, Lovely Profession
al University
<script>
var text = "HELLO WORLD";
[Link]("demo").innerHTML =
[Link](0);
</script
61
Dr. Navneet Kaur, Lovely Profession
al University
Property Access [ ]
Example
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
[Link]("demo").innerHTML = text[0];
</script>
63
Dr. Navneet Kaur, Lovely Profession
al University
<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = [Link](" ",text2);
[Link]("demo").innerHTML = text3;
</script>
64
Dr. Navneet Kaur, Lovely Profession
al University
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = [Link](7,13);
[Link]("demo").innerHTML = part;
</script>
65
Dr. Navneet Kaur, Lovely Profession
al University
<script>
let str = "Apple, Banana, Kiwi";
[Link]("demo").innerHTML =
[Link](7,13);
</script
66
Dr. Navneet Kaur, Lovely Profession
al University
<script>
let str = "Apple, Banana, Kiwi";
[Link]("demo").innerHTML = [Link](7,6);
</script>
67
Dr. Navneet Kaur, Lovely Profession
al University
References
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
78
Dr. Navneet Kaur, Lovely
Professional University
Program link
[Link]
79
Dr. Navneet Kaur, Lovely Profession
al University
Thank you