0% found this document useful (0 votes)
9 views31 pages

Module VI UNIT 2 Updated 2

This document provides an overview of interactivity using JavaScript, detailing its role in creating dynamic web pages and applications. It covers JavaScript syntax, basic concepts, variables, data types, operators, and practical examples of interactivity through HTML and JavaScript. Additionally, it explains statements, expressions, comments, and type conversions, emphasizing best practices for writing clean and effective code.

Uploaded by

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

Module VI UNIT 2 Updated 2

This document provides an overview of interactivity using JavaScript, detailing its role in creating dynamic web pages and applications. It covers JavaScript syntax, basic concepts, variables, data types, operators, and practical examples of interactivity through HTML and JavaScript. Additionally, it explains statements, expressions, comments, and type conversions, emphasizing best practices for writing clean and effective code.

Uploaded by

turkiosman2015
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 2

INTERACTIVITY USING JAVASCRIPT


2.1 Overview of Interactivity Using JavaScript
• JavaScript executes on the browser.
• It turns static HTML web pages into interactive pages by dynamically
updating content, validating forms, controlling multimedia, animating
images, and more.
• It is the third most important technology after HTML and CSS.
• JavaScript can be used to create web / mobile apps, servers, and games.
• Common uses: data validation, popup messages, handling HTML events,
modifying CSS.
• Created in 1995 by Brendan Eich (Netscape).
First named Mocha → LiveScript → JavaScript.

Example: Interactivity Using HTML + CSS + JS

<!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

 JavaScript runs in browsers and other devices ([Link]).


1
 Can be written inside <script> tags or in .js files.
 Uses Unicode character set.
 Case-sensitive (myFunction ≠ MyFunction).
 Variables can be declared with var, let, or without keywords.
 Semicolons separate statements.
 Multiple whitespaces are ignored.
 Comments use // or /* */.
 Strings use ' ' or " ".
 Numbers include integers, floats, hex.
 Booleans use true and false.
 Keywords cannot be used as variable names.

Example: HTML File with Basic JavaScript Syntax


<!DOCTYPE html>
<html>
<body>

<h2 id="heading">Original Text</h2>

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

 Declared using var, let, const.


2
 let = recommended.
 const = constant value (cannot change).
 Default value of unassigned variable = undefined.
 Multiple variables can be declared in one line.
 JavaScript allows dynamic typing.
 Constant objects can have updated properties.
 Variable names must follow rules (letters, digits, $, _ but cannot start with
digit).
 Scope:

o Global = outside any function.


o Local = inside function.
 Variables without var/let become global (not recommended).

HTML + JS Example: let, const, dynamic typing

!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

Joins two or more strings.

"Hello " + "World"

3. Comparison Operators

Used to compare values (true/false result).

 = = equal (checks value only)


 = = = strict equal (checks value + type)
 != not equal
 > greater than
 < less than
 >= greater or equal
 <= less or equal

4. Logical Operators
Used to combine conditions.

 && AND (both true)


 || OR (one true)
 ! NOT (reverses condition)

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>

let a = 5, b = 10, c = "5";


let output =
"Arithmetic: " + (a + b) + "<br>" +
"Comparison == : " + (a == c) + "<br>" +
"Comparison === : " + (a === c) + "<br>" +
"Logical AND : " + ((a < b) && (b > 3)) + "<br>" +
"Ternary : " + (a > b ? a : b);
[Link]("result").innerHTML = output;
</script>

[Link] JavaScript Data Types


Primitive Types (Simple, basic data types)
• String
Represents text. Written inside quotes.
Example: "Hello"
• Number
Represents numeric values (both whole numbers and decimals).
Example: 10, 3.14
• BigInt
Represents very large integers that Number cannot handle.
Example: 12345678901234567890n
• Boolean
Represents a true/false value.
Example: true, false
• Null
Represents an intentionally empty value (nothing).
Example: let x = null;

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>

2.1.2 Statements, Expressions, and Comments


Statements
• Statements perform actions. They tell the program what to do.
Example:
let x = 5; // action: create a variable
[Link](x); // action: print output
Expressions
• Expressions produce values. They are pieces of code that return a result.
Example:
5+3 // produces 8
"Hello" + "!" // produces "Hello!"
x > 10 // produces true or false

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

• A computer program is a list of "instructions" to be "executed" by a computer.


• In a programming language, these programming instructions are called
statements.
• A JavaScript program is a list of programming statements.
• In HTML, JavaScript programs are executed by the web browser.
o A program = many instructions.
o Each instruction = a JavaScript statement.
o When JavaScript is placed inside HTML, the browser executes the
statements one-by-one.

Example:

<script>
alert("Welcome!");
[Link]("Program started");
</script>

JavaScript Statements

JavaScript statements are composed of  Values, Operators, Expressions, Keywords,


and Comments.
11
Explanation of each part:

 Values: numbers, strings


Example: 5, "Hello"
 Operators: + - * / ==
 Expressions: produce values
 Keywords: let, var, if, for
 Comments: text ignored by JS
Example: // this is a comment

This statement tells the browser to write "Hello World." inside an HTML element
with id="demo":

Example

[Link]("demo").innerHTML = "Hello World.";

 Finds the element <p id="demo">...</p>


 Writes "Hello World." inside it

Most JavaScript programs contain many JavaScript statements.


The statements are executed, one by one, in the same order as they are written.
JavaScript programs (and JavaScript statements) are often called JavaScript code.

JavaScript always runs from top → bottom, unless controlled by loops or functions.

Semicolons

Semicolons separate JavaScript statements.

Semicolons tell JavaScript where one statement ends.

Add a semicolon at the end of each executable statement:

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

When separated by semicolons, multiple statements on one line are allowed:


a = 5; b = 6; c = a + b;
12
You can write everything on one line, but it reduces readability.

NB. JavaScript uses "Automatic Semicolon Insertion (ASI)" but can fail in complex
cases.
So, always ending with ; is safer.

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it
more readable.

Examples (original):

let person = "Hege";


let person="Hege";

o Both work the same.


o Spaces only help humans read code better.

A good practice is to put spaces around operators ( = + - * / ):

Spaces make code cleaner and easier to understand.

Type Conversions

• Learn how to explicitly convert values between different data types using
functions like parseInt() and toString().
• Understand implicit conversions and potential pitfalls.

5.1 Explicit Type Conversion


Explicit conversion means you convert the data type yourself using built-in functions.
JavaScript will not decide automatically  you tell it what to convert.

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

Converts a string into a floating-point number (a decimal).


parseFloat("3.14");

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

Converts a number (or any data type) into a string.


let num = 50;
let txt = [Link]();
[Link](txt); // "50"
[Link](typeof txt); // string

5.2 Implicit Conversion (Automatic)


Implicit conversion happens when JavaScript automatically changes the
data type to make expressions work.
JavaScript decides this by itself depending on context.

Examples:

1. String + Number → String


[Link]("5" + 3); // "53"
When using + with a string, JavaScript converts the number to a string.
2. Number - String → Number
[Link]("10" - 2); // 8
Here JavaScript converts "10" into a number, because subtraction is numeric.
3. Boolean → Number
[Link](true + 1); // 2 (true becomes 1)
14
[Link](false + 5); // 5 (false becomes 0)
4. null → 0
[Link](null + 3); // 3
5. undefined → NaN
[Link](undefined + 2); // NaN
2.3 Control Structures and Loops
2.3.1 Conditional Statements
 Use conditional statements to control how your program behaves based on
true/false conditions.
 JavaScript supports if, else if, and else to handle different decision paths.
 if runs code only when its condition is true.
if(boolean expression)
{
// code to be executed if condition is true
}
 else runs code when the if-condition is false.
if(condition expression)
{
//Execute this code..
}
else{
//Execute this code..
 else if handles additional conditions after an if.
if(condition expression)
{
//Execute this code block
}
else if(condition expression){
//Execute this code block
}
Note :Example on page 613 - 615
• Use "else if" condition when you want to apply second level condition after if
statement.
• Multiple else if statements are allowed, but only one else can be used.

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>

2.6 Document Object Model (DOM)


The Document Object Model (DOM) represents HTML documents in a tree-like
structure.
Each element in an HTML document is represented as a node in this tree. JavaScript
can navigate and access specific elements in the DOM using their IDs, classes, or
names.
By manipulating the DOM, web pages can become dynamic and interactive.
<p id="text">Hello World</p>
<button onclick="changeText()">Click</button>
<script>
function changeText() {
[Link]("text").innerHTML = "DOM Updated!";
}
</script>
JavaScript Arrays
A variable can hold only one value and cannot store multiple values at the same time.
A JavaScript array is a special type of variable that can store multiple values using a
special syntax.

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

Using Events with HTML Attributes


Events can be assigned directly to HTML elements using event attributes such as
onclick.
Example:
onclick="JavaScript"
Calling a Function from an Event
An event can trigger a function to execute JavaScript code when an action occurs.
Assigning Events Using the HTML DOM
Events can be assigned using JavaScript through the DOM by selecting an element
and assigning an event to it.
28
onload and onunload Events
 onload is triggered when the page loads.
 onunload is triggered when the user leaves the page.
These events can be used to check browser information or manage cookies.
oninput Event
The oninput event executes while the user enters data into an input field.
onchange Event
The onchange event occurs when the content of an input field is changed and focus
is lost. It is commonly used with input validation.
Practical Activity
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CTE DOM and Array Activity</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
}

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

You might also like