Module VI UNIT 2 Updated 2
Module VI UNIT 2 Updated 2
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width: 150px;
height: 150px;
background: orange;
transition: 0.3s;
}
</style>
</head>
<body>
<h2>JavaScript Interactivity Demo</h2>
<div id="box"></div>
<button onclick="changeColor()">Change Color</button>
<script>
function changeColor() {
[Link]("box").[Link] = "green";
}
</script>
</body>
</html>
2.2 JavaScript Syntax and Basic Concepts
<script>
// single line comment
var name = "Abebe";
let id = 10;
/*
multi line
comment
*/
[Link]("heading").innerHTML = "Updated
with JavaScript!";
</script>
</body>
</html>
2.2.1 Variables, Data Types, and Operators
[Link] Variables
Variable = stores data that can change.
!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let msg;
msg = "Hello JavaScript!";
let num1 = 100;
let num2 = num1;
const person = {name: "Abebe"};
[Link] = "Bill"; // allowed
[Link]("demo").innerHTML =
msg + "<br>" + num1 + "<br>" + num2 + "<br>" + [Link];
</script>
</body>
</html>
[Link] JavaScript Operators
1. Arithmetic Operators
+ add
- subtract
* multiply
/ divide
% remainder
++ increase by 1
3
-- decrease by 1
2. String Concatenation
3. Comparison Operators
4. Logical Operators
Used to combine conditions.
5. Assignment Operators
Used to assign values.
= assign
+ = add and assign
- = subtract and assign
* = multiply and assign
/ = divide and assign
% = remainder and assign
6. Ternary Operator
Short way to write an if-else.
condition? value1 : value2
4
Example:
age > 18 ? "Adult" : "Minor";
example
<script>
5
• Undefined
Represents a variable that has been declared but not given a value.
Example:
let x; // undefined
Structural Types (Complex data structures)
• Object
o A collection of key–value pairs used to store structured data.
o Each value is stored under a name (key).
o Useful for storing detailed information about one thing.
Example:
let student = {
name: "Ali",
age: 20,
grade: "A"
};
• Array
o An ordered list of values stored inside square brackets.
o Arrays keep values in a sequence
o Each item has an index (position).
o Index starts at 0.
Example
let numbers = [10, 20, 30, 40];
• Date
o The Date object is used to work with dates and times (year,
month, day, hour, etc.).
Example:
let today = new Date();
6
PRACTICAL EXERCISE
<!DOCTYPE html>
<html>
<head>
<title>EIS Riyadh – JavaScript Practical Exercise</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f4f4f4;
padding: 20px;
}
h1 {
color: #003366;
}
#box {
width: 150px;
height: 150px;
background: orange;
transition: 0.3s;
margin-bottom: 20px;
}
button {
padding: 10px 15px;
margin: 5px;
background: #003366;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background: #0055aa;
}
#output, #dataOutput {
background: white;
padding: 15px;
border-radius: 5px;
margin-top: 15px;
border: 1px solid #ccc;
}
</style>
7
</head>
<body>
<h1>EIS Riyadh – JavaScript Interactivity Practice</h1>
<p>Click the buttons to see how JavaScript changes the
webpage.</p>
<!-- INTERACTIVE BOX -->
<div id="box"></div>
<button onclick="changeColor()">Change Color</button>
<button onclick="resizeBox()">Resize Box</button>
<!-- OUTPUT AREA -->
<h2>JavaScript Output</h2>
<div id="output">Click a button to show results here...</div>
<!-- DATA TYPES + OBJECT + ARRAY -->
<h2>Data Types & Objects Example</h2>
<button onclick="showData()">Show School Info</button>
<div id="dataOutput"></div>
<script>
// ========= INTERACTIVITY =========
function changeColor() {
[Link]("box").[Link] = "green";
}
function resizeBox() {
[Link]("box").[Link] = "200px";
[Link]("box").[Link] = "200px";
}
// ========= VARIABLES + OPERATORS + OUTPUT =========
function calculate() {
let a = 5, b = 10, c = "5";
let output =
"<strong>Arithmetic:</strong> " + (a + b) + "<br>" +
"<strong>Comparison == :</strong> " + (a == c) + "<br>" +
"<strong>Comparison === :</strong> " + (a === c) + "<br>" +
"<strong>Logical AND :</strong> " + ((a < b) && (b > 3)) +
"<br>" +
"<strong>Ternary:</strong> " + (a > b ? a : b);
[Link]("output").innerHTML = output;
}
// Auto run calculation on page load
calculate();
// ========= OBJECT + ARRAY + DATE =========
function showData() {
// Object
8
const school = {
name: "Ethiopian International School (EIS) Riyadh",
established: 1994,
country: "Saudi Arabia, Riyadh"
};
// Array
let programs = ["KG", "Primary", "Middle School", "High
School"];
// Date
let today = new Date();
let result =
"<strong>School Name:</strong> " + [Link] + "<br>" +
"<strong>Established:</strong> " + [Link] +
"<br>" +
"<strong>Location:</strong> " + [Link] + "<br><br>" +
"<strong>School Programs:</strong> " + [Link](", ") +
"<br><br>" +
"<strong>Today's Date:</strong> " + [Link]();
[Link]("dataOutput").innerHTML = result;
}
</script>
</body>
</html>
9
Controlled using:
• if / else
Used to make decisions based on conditions.
if (x > 10) {
[Link]("Big");
} else { [Link]("Small"); }
• Loops (for, while)
Used to repeat actions.
For loop example:
for (let i = 0; i < 5; i++) {
[Link](i); }
While loop example:
let i = 0;
while (i < 5) {
[Link](i);
i++;
}
• Functions
Used to group actions and reuse code.
function greet() {
[Link]("Hello!");
}
greet(); // calling the function
Example
<p id="output"></p>
<script>
10
// statement: declaring variables
let x = 5;
let y = 6;
// expression: x + y
let z = x + y;
// conditional statement
if (z > 10) {
z = z + 1;
}
// loop statement
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i; // expression inside loop
}
// displaying in HTML
[Link]("output").innerHTML =
"z = " + z + "<br>" +
"Sum = " + sum;
</script>
JavaScript Programs
Example:
<script>
alert("Welcome!");
[Link]("Program started");
</script>
JavaScript Statements
This statement tells the browser to write "Hello World." inside an HTML element
with id="demo":
Example
JavaScript always runs from top → bottom, unless controlled by loops or functions.
Semicolons
Examples (original):
a = 5;
let a, b, c; // Declare 3 variables
// Assign the value 5 to a
b = 6;
// Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
NB. JavaScript uses "Automatic Semicolon Insertion (ASI)" but can fail in complex
cases.
So, always ending with ; is safer.
JavaScript ignores multiple spaces. You can add white space to your script to make it
more readable.
Examples (original):
Type Conversions
• Learn how to explicitly convert values between different data types using
functions like parseInt() and toString().
• Understand implicit conversions and potential pitfalls.
parseInt()
Converts a string → number
It stops reading when it reaches a non-numeric character.
let n = parseInt("123");
[Link](typeof n); // number
parseInt("abc"); // not a number
13
parseFloat()
Number()
Converts any valid data into a number.
It is stricter than parseInt() or parseFloat() → the whole value must be numeric.
Number("20.5"); // 20.5
Number("40px"); // NaN (because "px" is invalid)
Number(true); // 1
Number(false); // 0
Number(""); // 0
toString()
Examples:
15
• curly braces { } is not required when if block contains only a single line to
execute.
• Use comparison operators carefully when writing conditional expression.
• Differences between == (allows type conversion) and === (strict
comparison)
• Use else statement when you want to execute the code every time when if
condition evaluates to false.
• The else statement must follow if or else if statement.
• Multiple else block is NOT allowed.
2.3.2 Looping Structures
• Loops allow repeating code efficiently.
• Iterate through sequences of data effectively using for, while, and do-while
loops.
• Understand nested loops and their applications.
• JavaScript includes for, while, and do-while loops like Java or C#, to execute
code repeatedly.
The for loop
for (initializer; condition; iteration)
{ // Code to be executed }
o Initializer → starting value
o Condition → loop runs while this is true
o Iteration → update step (e.g., i++)
Key points:
• for loops repeat code based on conditions
• All three parts must be separated by semicolons
• Initializer can be placed outside the loop when needed
2.3.3 Break and Continue Statements
Used to manage loop flow using break to exit and continue to skip iterations.
16
• break → immediately stops a loop
• continue → skips to the next iteration
The break statement immediately stops the loop when a condition is met.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break; // stops the loop when i becomes 3
}
[Link](i);
}
The continue statement skips the current loop iteration but continues with the next
one.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skips printing 3
}
[Link](i);
}
2.3.4 Error Handling
• JavaScript does not show errors during compilation because it is a loosely-
typed language.
• It does not give compile-time errors.
• Errors appear only when the code runs (runtime errors).
• To handle these errors safely, JavaScript uses the try…catch…finally structure
• JavaScript does not show compile-time errors, so try…catch…finally helps
manage runtime errors safely.
Parts of Error Handling
• try → contains code that might cause an error
• catch(ex) → runs only if an error happens; gives details about the error
• finally → always runs, whether there was an error or not
17
• throw → used to manually create (throw) a custom error
Note:
• try…catch cannot fix syntax (grammar) errors in code.
• It only handles runtime errors.
Example1
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}
Example 2
try {
let a = b + 5; // b is not defined
} catch(ex) {
[Link]("Error happened: " + [Link]);
}
The finally block executes regardless of whatever happens.
Example: finally Block
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}
finally{
[Link]("message").innerHTML = "finally block
executed";
}
Throw
Uses throw keyword to raise a custom error.
Example
try
{
18
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}
You can use JavaScript object for more information about an error.
Example
try
{
throw {
number: 101,
message: "Error occurred"
};
}
catch (ex) {
alert([Link] + "- " + [Link]);
}
2.4 Functions in JavaScript
• Functions let you group code and reuse it.
• Defined using the function keyword, followed by a name, parameters, and a code
block.
• Functions make JavaScript code more readable, organized, reusable, and
maintainable.
function <function-name>(arg1, arg2, arg3,...)
{
//write function code here
};
2.4.1 Defining and Invoking Functions
• Functions are written using:
function functionName(parameters) { ... }
• They make code organized and reusable.
• A function runs only when called.
Example: Define a Function
function greet() { // defines a function named greet
alert("Hello World!");
19
}
Example: Calling a Function
greet ();
2.4.2 Function Expressions and Anonymous Functions
• A function expression in JavaScript is a function that is stored as a value, and
can be assigned to a variable or passed as an argument to another function.
• An anonymous function has no name
o Anonymous functions are typically used in functional programming e.g.
callback function,
o Anonymous functions are often used as arguments to other functions, and
are creating closure or immediately invoked function expression.
Example: Function Expression
var add = function (num1, num2) {
return num1 + num2;
};
var result = add(10, 20);//returns 30
Example: Anonymous Function
let numbers = [10, 20, 30, 40, 50];
let squareNumbers = [Link](function(number) {
return number * number;
});
2.4.3 Arrow Functions and Their Syntax
• Arrow functions are a shorthand syntax for defining anonymous functions in
JavaScript.
• They have compact syntax compared to anonymous functions.
• However, they do not have their own this value.
• Benefits: cleaner syntax and automatic return for one-line functions.
Example: Arrow Function
let square = num => num * num;
let result = square(5);
20
[Link](result); //25
Nested Functions (page 625 , pdf 645)
• In JavaScript, a function can have one or more inner functions.
• These nested functions are in the scope of outer function. Inner function can
access variables and parameters of outer function.
• However, outer function cannot access variables defined inside inner
functions.
2.4.4 Parameters, Arguments, and Default Values
• Functions accept input values through parameters.
You can:
• Pass different types of values
• Pass more or fewer arguments than the number of parameters
• Access all passed values using the arguments object
• You can also return values using return.
Example: Function Parameters
function greet(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}
greet("Abebe", "Jobs");
Practical exercise
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EIS-Riyadh Grade 12 – JavaScript Control Structures & Functions</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f4f4f4;
margin: 0;
padding: 20px;
}
h1, h2 {
text-align: center;
color: #004aad;
}
21
.container {
width: 90%;
margin: auto;
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
button {
padding: 10px 20px;
margin: 10px 0;
cursor: pointer;
border: none;
background: #004aad;
color: white;
border-radius: 5px;
font-size: 16px;
}
button:hover {
background: #0066cc;
}
#output {
background: #e8f0ff;
padding: 15px;
border-radius: 8px;
min-height: 150px;
white-space: pre-line;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>EIS–Riyadh Grade 12 JavaScript Demonstration</h1>
<h2>Control Structures, Loops, Error Handling & Functions</h2>
<div class="container">
<!-- Buttons for each demonstration -->
<button onclick="runConditionals()">1. Conditional Statements</button>
<button onclick="runLoops()">2. Looping Structures</button>
<button onclick="runBreakContinue()">3. Break & Continue</button>
<button onclick="runErrorHandling()">4. Error Handling</button>
<button onclick="runFunctions()">5. JavaScript Functions</button>
<!-- Output Display -->
<div id="output">Output will appear here...</div>
</div>
<script>
// ===============================
// 1. CONDITIONAL STATEMENTS
// ===============================
function runConditionals() {
let score = 85; // Example score of a Grade 12 JS student at EIS
22
let message = "Conditional Statements Example\n\n";
if (score >= 90) {
message += "Excellent! A+";
}
else if (score >= 80) {
message += "Very Good! B+";
}
else {
message += "Needs Improvement.";
}
// Strict vs Loose comparison example
let num = "100";
message += "\n\nLoose (==) comparison: " + (num == 100);
message += "\nStrict (===) comparison: " + (num === 100);
[Link]("output").innerText = message;
}
// ===============================
// 2. LOOPS (for, while, do-while)
// ===============================
function runLoops() {
let message = "Looping Structures Example\n\n";
message += "For Loop (1 to 5):\n";
for (let i = 1; i <= 5; i++) {
message += i + " ";
}
message += "\n\nWhile Loop (1 to 3):\n";
let a = 1;
while (a <= 3) {
message += a + " ";
a++;
}
message += "\n\nDo-While Loop (1 to 3):\n";
let b = 1;
do {
message += b + " ";
b++;
} while (b <= 3);
[Link]("output").innerText = message;
}
// ===============================
// 3. BREAK & CONTINUE
// ===============================
function runBreakContinue() {
let message = "Break & Continue Example\n\n";
message += "Break Example (stop at 3):\n";
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
message += i + " ";
}
message += "\n\nContinue Example (skip 3):\n";
23
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
message += i + " ";
}
[Link]("output").innerText = message;
}
// ===============================
// 4. ERROR HANDLING (try, catch, finally, throw)
// ===============================
function runErrorHandling() {
let message = "Error Handling Example\n\n";
try {
// Calling undefined function to generate runtime error
missingFunction();
}
catch (ex) {
message += "Caught Error: " + ex + "\n";
}
finally {
message += "Finally Block: Always runs.\n\n";
}
// Custom throw example
try {
throw { number: 101, message: "Custom EIS-Riyadh Error" };
}
catch (ex) {
message += "Custom Error → Number: " + [Link] + ", Message: " + [Link];
}
[Link]("output").innerText = message;
}
// ===============================
// 5. FUNCTIONS IN JAVASCRIPT
// ===============================
function runFunctions() {
let message = "Functions Demonstration\n\n";
// 1. Function Declaration
function greet() {
return "Hello Grade 12 Students at EIS-Riyadh!";
}
message += greet() + "\n\n";
// 2. Function Expression
let add = function(x, y) {
return x + y;
};
message += "Function Expression (10 + 20 = " + add(10, 20) + ")\n\n";
// 3. Anonymous Function (map)
let numbers = [2, 4, 6];
let squares = [Link](function(n) { return n * n; });
message += "Anonymous Function (Squares): " + [Link](", ") + "\n\n";
24
// 4. Arrow Function
let multiply = num => num * 5;
message += "Arrow Function (5 * 5 = " + multiply(5) + ")\n\n";
// 5. Nested Functions
function schoolInfo() {
let school = "EIS-Riyadh";
function classInfo() {
return "Grade 12 JavaScript Class at " + school;
}
return classInfo();
}
message += "Nested Function → " + schoolInfo();
[Link]("output").innerText = message;
}
</script>
</body>
</html>
25
Declaring an Array
An array is declared using square brackets and values are separated by commas.
Example:
let numArr = [10, 20, 30, 40, 50];
In this array, numArr is the name of the array variable, and it stores five numeric
values.
This method is called array literal syntax and it is the preferred way of creating
arrays.
Creating an Array Using the Array Constructor
Arrays can also be created using the Array() constructor.
Example:
let numArr = new Array(10, 20, 30, 40, 50);
Array Index
Every value stored in an array is associated with a numeric index starting from 0.
The index identifies the position of each element in the array.
Arrays can store different types of data such as:
Strings
Numbers
Decimal values
Boolean values
JavaScript arrays are not required to store the same type of values.
They can store mixed data types.
Example:
let data = [1, "Abebe", "DC", true, 255000, 5.5];
Getting the Size of an Array
The length property is used to get the total number of elements in an array.
The length changes when elements are added or removed.
Example:
[Link];
26
Accessing and Modifying Array Elements
Array elements can be accessed using the arrayName[index] syntax.
The index starts from zero.
Array values can be modified by assigning a new value to an existing index.
If a non-existing index is accessed, JavaScript returns undefined.
Using the at() Method
New browsers support the at(pos) method, which returns the element at a specified
index.
If a negative index is used, at() returns elements from the end of the array.
If the index does not exist, it returns undefined.
Iterating Through Arrays
Arrays can be iterated using:
forEach()
for loop
for...of loop
for...in loop
These methods allow accessing all elements of an array one by one.
Adding Elements to an Array
Elements can be added by assigning a value to a new index. If the index is greater
than the last index, new elements are added and empty indexes become undefined.
Adding Elements Using push()
The push() method adds a new element at the end of an array and is the
recommended method.
Adding Elements Using unshift()
The unshift() method adds one or more elements to the beginning of an array.
Removing Array Elements
pop() removes and returns the last element of an array.
shift() removes and returns the first element of an array.
Removing Middle Elements from an Array
27
Middle elements cannot be removed directly. A new array must be created using the
filter() method to exclude the unwanted element. The original array remains
unchanged.
Adding and Removing DOM Elements Dynamically
Elements can be added or removed from the DOM programmatically based on user
actions or other conditions. This helps in building complex and interactive user
interfaces.
Event Handling and Propagation
JavaScript can execute code when an event occurs, such as clicking a mouse or
typing a key. Event handling allows web pages to respond to user interactions.
Common HTML Events
Mouse click
Page load
Image load
Mouse movement
Input field change
Form submission
Key press
h2 {
color: #2c3e50;
}
.box {
background: #ffffff;
padding: 15px;
margin-bottom: 20px;
border-radius: 8px;
}
button {
padding: 8px 12px;
margin-top: 5px;
cursor: pointer;
}
ul {
list-style-type: square;
}
input {
padding: 6px;
margin-top: 5px;
29
}
</style>
</head>
<body onload="loadCities()">
<h2>CTE – DOM & JavaScript Arrays Practical</h2>
<!-- DOM Manipulation Section -->
<div class="box">
<h3>Document Object Model (DOM)</h3>
<p id="text">Hello World</p>
<button onclick="changeText()">Click</button>
</div>
<!-- Array Display Section -->
<div class="box">
<h3>JavaScript Arrays</h3>
<ul id="cityList"></ul>
<input type="text" id="cityInput" placeholder="Enter city name"
oninput="convertUpper()">
<br>
<button onclick="addCity()">Add City</button>
<button onclick="removeCity()">Remove Last City</button>
</div>
<script>
// DOM manipulation
function changeText() {
[Link]("text").innerHTML = "DOM Updated!";
}
// JavaScript Array
let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];
// Display array elements
function loadCities() {
let list = [Link]("cityList");
[Link] = "";
[Link](function(city) {
let li = [Link]("li");
[Link] = city;
[Link](li);
});
}
// Add element using push()
function addCity() {
let cityName = [Link]("cityInput").value;
if (cityName !== "") {
[Link](cityName);
loadCities();
[Link]("cityInput").value = "";
}
}
// Remove element using pop()
function removeCity() {
[Link]();
30
loadCities();
}
// oninput event
function convertUpper() {
let input = [Link]("cityInput");
[Link] = [Link]();
}
</script>
</body>
</html>
31