WAD LECTURE9and10
WAD LECTURE9and10
❖ JavaScript
2
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Example
Make a "Good day" greeting if the hour is less than 18:00:
3
The if Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
4
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax:
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
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
5
The else Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if...else Example</h2>
<p>Check if a person is an adult or a minor:</p>
<p id="demo"></p>
<script>
let age = 16; // Change this value to test different cases
let message;
if (age >= 18) {
message = "You are an adult.";
} else {
message = "You are a minor.";
}
document.getElementById("demo").innerHTML = message;
</script>
</body>
</html>
6
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day"
greeting, otherwise a "Good evening":
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The result of greeting will be:
Good day
7
The else if Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if...else if...else Example</h2>
<p>Check the age category of a person:</p>
<p id="demo"></p>
<script>
let age = prompt("Enter your age:"); // User enters their age
age = Number(age); // Convert the input to a number
let message;
if (age < 13) {
message = "You are a child.";
} else if (age >= 13 && age < 18) {
message = "You are a teenager.";
} else if (age >= 18 && age < 60) {
message = "You are an adult.";
} else {
message = "You are a senior citizen.";
}
document.getElementById("demo").innerHTML = message;
</script>
</body>
</html>
8
The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• If there is no match, the default code block is executed.
9
Example: Switch
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = “Saturday";
}
The result of day will be:
Sunday
10
The break Keyword
Note: If you omit the break statement, the next case will
be executed even if the evaluation does not match the
case.
11
The default Keyword
The default keyword specifies the code to run if there is no case match:
Example: The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
The result of text will be:
Today is Sunday
12
JavaScript Loops
Loops are handy, if you want to run the same code over
and over again, each time with a different value.
13
The For Loop
Example
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
14
The For Loop Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
15
The While Loop
The while loop loops through a block of code as long as a specified
condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example: In the following example, the code in the loop will run, over and
over again, as long as a variable (i) is less than 10:
16
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do {
// code block to be executed
}
while (condition);
Example: The example below uses a do while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed before the
condition is tested:
do {
text += "The number is " + i;
i++;
}
while (i < 10);
17
Functions
18
Function Invocation
19
Function Return
• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
• Functions often compute a return value. The return value is "returned" back to the
"caller":
Example: Calculate the product of two numbers, and return the result:
20
Types of Functions
• Regular Function
• Anonymous Function
• Arrow Function
• IIFE(Immediately Invoked Function Expression)
21
1. Regular Function
Definition
A regular function is a named function that can be
reused and called multiple times.
Example:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
22
Example(Regular)
<body>
<script>
// Regular Function
function greet(name) {
return "Hello, " + name + "!";
}
document.getElementById("regularOutput").innerText =
greet(“Ammar");
</script>
</body>
23
2. Anonymous Function
Definition
An anonymous function is a function without a name,
often assigned to a variable or passed as an argument.
Example:
const sum = function(a, b) {
return a + b;
};
console.log(sum(5, 10));
24
Example(Anonymous)
<body>
<h1>Anonymous Function in JavaScript</h1>
<p id="anonymous-function"></p>
<script>
// Anonymous Function Example
const sum = function(a, b) {
return a + b;
};
// Display output
document.getElementById("anonymous-function").innerText = "Sum of
7 and 8: " + sum(7, 8);
</script>
</body>
25
this keyword
Note: this is not a variable. It is a keyword. You cannot change the value of this.
26
this in a Method
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
27
this in Event Handlers
Example
<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
28
3. Arrow Function
Definition
An arrow function provides a concise syntax for
functions using => and does not have its own this
context.
Example:
const multiply = (x, y) => x * y;
console.log(multiply(4, 3));
29
3. Arrow Function (Before/After)
Before Arrow:
hello = function() {
return "Hello World!";
}
With Arrow Function:
hello = () => {
return "Hello World!";
}
It gets shorter! If the function has only one statement, and the statement
returns a value, you can remove the brackets and the return keyword:
Arrow Functions Return Value by Default:
hello = () => "Hello World!";
30
3. Arrow Function (Parameters)
Note: This works only if the function has only one statement.
In fact, if you have only one parameter, you can skip the parentheses as
well:
31
Example (Arrow)
<body>
<h1>Arrow Function in JavaScript</h1>
<p id="arrow-function"></p>
<script>
// Arrow Function Example
const multiply = (x, y) => x * y;
// Display output
document.getElementById("arrow-function").innerText =
"Multiplication of 6 and 5: " + multiply(6, 5);
</script>
</body>
32
Regular vs Anonymous vs Arrow
Differences:
• Syntax: Arrow functions are more concise
compared to regular or anonymous functions.
• this Binding: Regular and anonymous functions
have their own this, whereas arrow functions
inherit this from their surrounding scope.
• Usage: Regular functions are used for named
function declarations, anonymous functions for
callbacks, and arrow functions for concise function
expressions.
33
Callbacks
A callback is a function that is passed as an argument to another function and is
executed later, usually after a certain task is completed.
34
Callbacks Example
<body>
<h2>JavaScript Callback Function Example</h2>
<p>Check the console for output.</p>
<script>
// Function that takes a name and a callback function
function greet(name, callback) {
console.log("Hello, " + name);
callback(); // Execute the callback function
}
// Callback function
function sayBye() {
console.log("Goodbye!");
}
// Calling greet function with a callback
greet("Alice", sayBye);
</script>
</body>
35
JavaScript Events
HTML Events
• An HTML event can be something the browser does, or something a user
does.
36
fi
fi
Single Quote or Double Quote
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
37
Event Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
</body>
</html>
38
Common HTML Event
Events:
onchange: An HTML element has been changed
onclick: The user clicks an HTML element
onmouseover: The user moves the mouse over an HTML element
onmouseout: The user moves the mouse away from an HTML element
onkeydown: The user pushes a keyboard key
onload: The browser has nished loading the page
Example: LECTURE10.html
39
fi
ES6+ Features
40
Error Handling
41
fi
fi
fi
fi
fi
JavaScript try and catch
42
fi
fi
Example Try and Catch
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Error Handling</h2>
<p>How to use <b>catch</b> to display an error.</p>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
43
The throw Statement
Note: If you use throw together with try and catch, you can control program ow and
generate custom error messages.
44
fl
Example(Throw)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
45
The finally Statement
The nally statement lets you execute code, after try and catch, regardless
of the result:
Syntax
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
nally {
Block of code to be executed regardless of the try / catch result
}
46
fi
fi
Example (finally)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript nally Example</title>
</head>
<body>
<h1>JavaScript try...catch... nally Example</h1>
<button onclick="testErrorHandling()">Click to Test Error</button>
<p id="error-message"></p>
<script>
function testErrorHandling() {
try {
// Simulating an error
let result = 10 / unknownVariable; // `unknownVariable` is not de ned
} catch (error) {
// Handling the error
document.getElementById("error-message").innerText = "Error: " + error.message;
} nally {
// Always executes
console.log("Finally block executed!");
alert("Finally block executed!");
}
}
</script>
</body>
</html>
47
fi
fi
fi
fi