0% found this document useful (0 votes)
4 views25 pages

Chpter 4 - JavaScript

The document provides an overview of JavaScript, detailing its purpose, capabilities, and syntax. It covers various aspects such as DOM manipulation, event handling, data storage, and the creation of interactive web applications. Additionally, it explains JavaScript data types, variable declaration, and operators, making it a comprehensive guide for understanding JavaScript programming.

Uploaded by

besubosman
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)
4 views25 pages

Chpter 4 - JavaScript

The document provides an overview of JavaScript, detailing its purpose, capabilities, and syntax. It covers various aspects such as DOM manipulation, event handling, data storage, and the creation of interactive web applications. Additionally, it explains JavaScript data types, variable declaration, and operators, making it a comprehensive guide for understanding JavaScript programming.

Uploaded by

besubosman
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

6/30/2025

Previous Chapter Overview


Woldia Institute of Technology (IoT)  What CSS is and its purpose
 Types of CSS:
3. Background & Borders: background, background-color,
background-image, background-size, background-position,
◦ Inline, Internal, External background-repeat, background-attachment, border-radius,
School of Computing  Common Types of selectors box-shadow, border-collapse, border-spacing
◦ Element, ID, Class, Universal, 4. Color & Opacity: color, opacity, background-blend-mode, mix-
Group, Descendant, Child, Attribute blend-mode
Programming and Algorithm Development Chair Selector 5. Flexbox & Grid: display, flex, flex-direction, flex-wrap, flex-flow,
Common CSS Style Properties justify-content, align-items, align-self, align-content, order, flex-
1. Layout & Box Model: width, height, max- grow, flex-shrink, flex-basis, grid, grid-template-columns, grid-
width, max-height, min-width, min- template-rows, grid-template-areas, grid-gap, grid-column, grid-
height, margin, padding, border, border- row, place-items
Chapter Four: JavaScript (JS) width, border-style, border-color, display, 6. Transitions & Animations: transition, transition-property,
overflow, visibility, box-sizing, float, transition-duration, transition-timing-function, transition-delay,
clear, position, top, right, bottom, left, z- animation, animation-name, animation-duration, animation-
I n s tr uc to r N a m e : D E RS O M . ( M S C I N S W E N G . ) index, clip timing-function, animation-delay, animation-iteration-count,
2. Typography: font-family, font-size, font- animation-direction, animation-fill-mode, animation-play-state
weight, font-style, font-variant, letter- 7. Transformations: transform, transform-origin, rotate, scale,
JUNE 30, 2025 spacing, word-spacing, line-height, text- translate, skew, perspective
align, text-decoration, text-transform, 8. Visibility & Cursor: visibility, opacity, display, cursor, pointer-
direction, white-space, text-overflow events
9. Lists & Tables: list-style, list-style-type, list-style-position, list-
style-image, table-layout, caption-side, empty-cells
[Link]: content, quotes, resize, user-select, will-change

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024


WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 2

Introduction to JavaScript What can a JavaScript Do ?


 JavaScript is a most popular scripting language that is essential for adding 1. Manipulating HTML & CSS (DOM Manipulation)
interactivity and dynamic content to websites. • Change HTML content dynamically
 It runs on the client's browser, enabling web pages to respond to user ([Link]("id").innerHTML = "New Content";)
actions without needing to reload. • Modify styles ([Link]("id").[Link] = "red";)
 JavaScript is a high-level, dynamic, interpreted programming language • Show, hide, or animate elements
primarily used to add interactivity and behavior to web pages. 2. Handling Events
 Initially developed for client-side web development, JavaScript now • Respond to user actions like clicks, keypresses, mouse movements
powers web servers (via [Link]), mobile apps(React Native), and • [Link]("click", function() { alert("Button Clicked!"); });
desktop applications. 3. Validating Forms
 JavaScript is widely used for front-end and back-end web development, • Ensure correct user input before submitting a form
enabling features like form validation, animations, and asynchronous • Example: Check if an email is entered correctly
operations. 4. Creating Interactive Elements
 JavaScript is an interpreted language (means that scripts execute without • Dropdowns, carousels, modals, and tooltips
preliminary compilation)

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 3 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 4
6/30/2025

What can a JavaScript Do ? JavaScript Syntax


5. Handling AJAX & Fetch Requests
• Fetch data from APIs without reloading the page  The Web browser runs a JavaScript program when the Web page is
• fetch("[Link] => [Link]()).then(data => first loaded, or in response to an event.
[Link](data));  JavaScript programs can either be placed directly into the HTML file
6. Storing Data Locally or they can be saved in external files.
• Use localStorage and sessionStorage to store user preferences or session data  JavaScript can be implemented using JavaScript statements that are
• [Link]("username", “NolawiM"); placed within the <script>... </script> HTML tags in a web page.
7. Creating Web Applications
• Used with frameworks like React, Angular, and Vue to build dynamic web apps
8. Game Development
 JavaScript commands and names are case-sensitive.
• Can be used with Canvas API, WebGL, or game engines like Phaser  JavaScript command lines end with a semicolon to separate it
6. Server-Side Development from the next command line in the program.
• With [Link], JavaScript can be used to create backend services and APIs • in some situations, the semicolon is optional
7. Building Hybrid Mobile & Desktop Apps • semicolons are useful to make your code easier to follow and
• React Native (for mobile apps) interpret.
• [Link] (for desktop apps)

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 5 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 6

Methods of Using JavaScript JavaScript Comments


1. Placing a program in an external 2. JavaScript can be embedded  Any text between a // and the end of a line is treated as a
file allows you to hide the program in HTML documents: in the comment and is ignored by JavaScript.
code from the user <head>, in the <body>, or in  Any text between the characters /* and */ is treated as a
both.
comment. This may span multiple lines.

3. JavaScript object attributes can be placed in HTML element tags.


e.g., <body onLoad="alert(JavaScript in Web Programming')">
@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 7 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 8
6/30/2025

Basics of JavaScript Input Basics of JavaScript Input


 prompt(): This function displays a dialog box where the  confirm(): This function displays a dialog box with a
user can type text. message and two buttons ("OK" and "Cancel"). Use it for
• Prompts user for text input, returns the typed string. simple yes/no decisions.
• Can specify a default value as the second argument. • Presents a message and two buttons ("OK" and
• Limited to capturing single-line text, not ideal for complex "Cancel").
data. • Returns true if "OK" clicked, false for "Cancel".
• Use for making simple yes/no decisions.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 9 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 10

Basics of JavaScript Input Basics of JavaScript Input


 HTML Forms: Create forms with various input elements like text
fields, checkboxes, radio buttons, and dropdown menus.

• Capture input using [Link]() or


[Link]().

• Use event listeners like onchange or onsubmit to handle user


interaction.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 11 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 12
6/30/2025

Basics of JavaScript Output Basics of JavaScript Output


 [Link](): This function prints messages to the  alert(): This function displays a modal dialog box with a
browser's developer console for debugging purposes. message. Use it sparingly as it can interrupt the user
• Primarily for debugging, prints messages to the browser's experience.
developer console. • Displays a modal dialog box with a message, blocking user
• Useful for inspecting variables, values, and program flow interaction until dismissed.
during development. • Use sparingly as it can disrupt user experience.
• Consider less intrusive methods like toasts or notifications
for alerts.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 13 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 14

Basics of JavaScript Output Basics of JavaScript Output


 HTML Elements: Modify the content of HTML elements  JavaScript provides [Link]() and
like paragraphs, headings, and lists using JavaScript to [Link]() to write text to a Web page
dynamically update the page. • Those functions are used to write content directly to an
• Access and modify element content using innerHTML, HTML document. However, there are some key differences
innerText, or specific properties like value. between them:
• Dynamically update page content based on user interactions • [Link](): This function writes the specified content
or calculations. to the document without adding a newline character at the
end.
• [Link](): This function does the same as
[Link](), but it also adds a newline character (\n) at
the end of the content.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 15 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 16
6/30/2025

Variables in JavaScript JavaScript Data Types


 Variables store data values and are declared using:  JavaScript has two main categories of data types:
 Variables: 1. Primitive Data Types (Immutable, stored by value)- These are basic
data types that hold a single value.
• let: Block-scoped variable, can be reassigned.
Data Type Example Description
• const: Block-scoped variable, cannot be reassigned.
Number let x = 10; Represents integers and floating-point numbers
• var: Function-scoped variable, hoisted (avoid using in modern JS).
String Text enclosed in single ('), double (") or
let name = “Nolawi";
backticks (`)
Rules for Variable Names Boolean let isReady = true; Represents true or false
• Must start with a letter, _, or $. Undefined let a; A variable declared but not assigned a value
• Can contain letters, numbers, _, or $. Null let b = null; Represents an intentional empty value
• Case-sensitive (myVar and myvar are different). BigInt let bigNum = Used for large numbers beyond Number limits
• Cannot be a JavaScript keyword (e.g., let, const, function). 9007199254740991n;
Symbol let id = Creates unique and immutable identifiers
Symbol("unique");
@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 17 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 18

JavaScript Data Types Example JavaScript Variables


 JavaScript has two main categories of data types:
2. Non-Primitive (Reference) Data Types (Mutable, stored by
reference) - These hold collections of values and are mutable.

Data Type Example Description


Object let person = {name: “Nolawi", age: 25}; A collection of key-value
pairs
Array let numbers = [1, 2, 3, 4]; A special type of object
for ordered lists
Function function greet() { return "Hello"; } A reusable block of code

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 19 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 20
6/30/2025

Example JavaScript Variables Example JavaScript Variables

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 21 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 22

Operators in JavaScript 1. Arithmetic operators


 Used to perform mathematical operations on numbers.
 JavaScript provides a variety of basic operators that allow
Operator Description Example Result
you to perform operations on values and variables.
+ Addition 5+3 8
- Subtraction 10 - 4 6
 These operators can be categorized into several types, such * Multiplication 2*3 6
as arithmetic, comparison, logical, assignment, and more.
/ Division 10 / 2 5
% Modulus (Remainder) 10 % 3 1
** Exponentiation (ES6) 2 ** 3 8
++ Increment let x = 5; x++ 6
-- Decrement let y = 5; y-- 4

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 23 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 24
6/30/2025

2. Comparison Operators 3. Logical Operators 4. String Operators


 Used to compare two values and return a boolean (true or false).  Logical operators: used to combine or manipulate boolean values.
Operator Description Example Result
Operator Description Example Result
&& Logical AND true && false false
== Equal to (loose equality) 5 == "5" true
|| Logical OR true || false true
=== Equal to (strict equality) 5 === "5" false
! Logical NOT !true false
!= Not equal to (loose) 5 != "6" true
!== Not equal to (strict) 5 !== "5" true
> Greater than 10 > 5 true
 String operators: used to concatenate strings.
< Less than 10 < 5 false
Operator Description Example Result
>= Greater than or equal to 10 >= 10 true
+ Concatenation "Hello" + " World" "Hello World"
<= Less than or equal to 10 <= 5 false
Concatenation
+= let str = "Hi"; str += "!" "Hi!"
assignment
@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 25 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 26

5. Assignment Operators 6. Bitwise Operators


 Used to assign values to variables.  Used to perform operations on binary representations of
numbers.
Operator Description Example Result
Operator Description Example
= Assignment let x = 5; x=5
& Bitwise AND Examines each bit position
+= Addition assignment x += 3 x=x+3
| Bitwise OR If either bit of the operands is 1, the
-= Subtraction assignment x -= 2 x=x-2 result will be 1
*= Multiplication assignment x *= 4 x=x*4 ^ Bitwise XOR Set the result bit, only if either bit is
/= Division assignment x /= 2 x=x/2 1, but not both
%= Modulus assignment x %= 3 x=x%3 << Bitwise left shift Shifts the bits of an expression to the
**= Exponentiation assignment x **= 2 x = x ** 2 left
>> Bitwise signed right Shifts the bits to the right, and
shift maintains the sign

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 27 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 28
6/30/2025

7. Ternary Operator 8. Type Operators 9. Optional Chaining & Nullish Coalescing Operator(ES11)

 Ternary (Conditional) Operator: used as a shorthand for if-else  Optional Chaining Operator (ES11): used to safely access nested
statements. properties without causing errors.
Operator Description Example Result Operator Description Example Result
?: Ternary operator let result = (5 > 3) ? "Yes" : "No"; "Yes" Optional undefined (if user is null
?. let name = user?.name;
chaining or undefined)

 Type Operators: used to check the type of a variable or object.  Nullish Coalescing Operator (ES11): used to provide a default
value for null or undefined.
Operator Description Example Result
typeof Returns the type of a value typeof "Hello" "string" Operator Description Example Result
let x = null ??
Checks if an object is an ?? Nullish coalescing "default"
instanceof [] instanceof Array true "default";
instance of a class

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 29 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 30

Control Structures Conditional Statements


 Control structures provide the "flow" of your JavaScript programs,  Conditional statements allow you to execute different code
allowing you to make decisions and repeat actions based on certain based on the evaluation of a condition.
conditions.
 If statement: It executes a block of code if a specified condition is
 Mastering these structures is crucial for writing flexible and efficient true.
code.
 If...else statement: It executes one block of code if a condition is
true and another block of code if the condition is false.
 Else if statement: It allows you to check multiple conditions and
execute the corresponding block of code based on the first true
condition.
 Switch statement: It evaluates an expression against multiple cases
and executes the code block associated with the matching case.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 31 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 32
6/30/2025

Conditional Statements Conditional Statements


 If statement:  Ternary Operator: The ternary operator is a concise way to write
simple if … else statements.

 If … else if statement:
 If … else statement:

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 33 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 34

Conditional Statements Looping Statements


 Switch Statement: The switch statement is used to perform  Loops are used to repeatedly execute a block of code.
different actions based on different conditions. • For loop: It repeatedly executes a block of code for a specified
number of times.
• While loop: It executes a block of code as long as a specified
condition remains true.
• Do...while loop: It executes a block of code once and then repeats it
as long as a specified condition is true.
• For...in loop: It iterates over the properties of an object.
• For...of loop: It iterates over iterable objects, such as arrays or strings.
• forEach method: Specifically used with arrays to iterate over each
element.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 35 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 36
6/30/2025

Looping Statements Looping Statements


 for loop:  do … while loop:  For … in loop:
• Iterates over the enumerable properties of an object.

 while loop:

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 37 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 38

Looping Statements Looping Statements

 For … of loop:  forEach Method:


• Iterates over the values of an iterable object (arrays, strings, etc.). • Specifically used with arrays to iterate over each element.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 39 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 40
6/30/2025

Jump Statements Jump Statements


 Break statement: It terminates the current loop, switch, or  break: Used to exit a loop.
labeled statement.  continue: Skips the rest of the loop and continues with the next
iteration.
 Continue statement: It skips the current iteration of a loop and
proceeds to the next iteration.
 Return statement: It terminates the execution of a function and
returns a value to the caller.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 41 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 42

Try-Catch Statement: Arrays in JavaScript


 Used for handling errors/exceptions.  Arrays are a fundamental data structure in JavaScript, allowing
you to store and manipulate collections of values.

 Array Declaration:
• You can create an array using square brackets [ ] and initialize it
with values.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 43 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 44
6/30/2025

Arrays in JavaScript Arrays in JavaScript


 Accessing Elements:  Array Methods:
• Elements in an array can be accessed using zero-based indexing. a. Push and Pop:
• push: Adds elements to the end of an array.
• pop: Removes the last element from the end of an array.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 45 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 46

Arrays in JavaScript Arrays in JavaScript


 Array Methods:  Array Methods:
b. Shift and Unshift: c. Slice:
• unshift: Adds elements to the beginning of an array. • Creates a shallow copy of a portion of an array.
• shift: Removes the first element from the beginning of an
array. Syntax: [Link](start?: number | undefined, end?: number | undefined)

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 47 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 48
6/30/2025

Arrays in JavaScript Arrays in JavaScript


 Array Methods:  Array Methods:
d. Splice: e. concat:
• Changes the contents of an array by removing or replacing • Merges two or more arrays, returning a new array.
existing elements and/or adding new elements.

Syntax: [Link](start: number, deleteCount: number, ...items: number[])

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 49 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 50

Arrays in JavaScript Arrays in JavaScript


 Array Methods:  Array Length:
f. forEach:  You can get the length of an array using the length property.
• Executes a provided function once for each array element.

 Multidimensional Arrays:
 Arrays can also contain
other arrays, creating
multidimensional arrays.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 51 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 52
6/30/2025

Arrays in JavaScript Functions in JavaScript- Definition


 Array Iteration:  What is a Function?
 Arrays can be • A reusable block of code that performs a specific task.
iterated using
loops like for • Functions can take inputs (parameters) and return outputs.
and forEach, or • They are defined using the function keyword, followed by a
using array name, parentheses, and a function body enclosed in curly
methods like braces. The functions are optionally return a value to the
map, filter, etc. caller

 Why Use Functions?


• Code reusability.
• Modularity and organization.
• Easier debugging and maintenance.
@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 53 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 54

Functions in JavaScript- Types of Functions Functions in JavaScript- Types of Functions


 Named Functions:  Anonymous Functions:
• Functions declared with a name
• Hoisted (can be called before declaration). • Functions without a name, often used as callbacks or assigned
• Useful for reusable code blocks. to variables.
• Not hoisted (must be defined before use).
• Commonly used in event listeners or as arguments to other
functions.

 Hoisting is a JavaScript behavior where variable and function declarations are


moved (hoisted) to the top of their containing scope during compilation before
code execution.
 How Hoisting Works:
• Function declarations are fully hoisted.
• Var declarations are hoisted but not initialized.
• Let and const declarations are hoisted but remain in the "temporal dead zone"
until they are initialized.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 55 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 56
6/30/2025

Functions in JavaScript- Types of Functions Functions in JavaScript- Types of Functions

 Arrow Functions (ES6+):  Immediately Invoked Function Expression (IIFE):


• A concise syntax for writing functions, introduced in ES6. • A function that is executed immediately after it's created.
• Shorter syntax. • Used to create a private scope.
• No this binding (inherits this from the parent scope). • Avoids polluting the global namespace.
• Implicit return for single-line functions.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 57 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 58

Functions in JavaScript- Types of Functions Functions in JavaScript- Types of Functions

 Recursive Functions:  Higher-Order Functions:


• A function can call itself, creating a recursive function. • Functions can take other functions as parameters or return
them.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 59 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 60
6/30/2025

Functions in JavaScript- Types of Functions Functions in JavaScript- Types of Functions

 Async Functions (ES7+):  Closures:


• Functions that return a promise and allow the use of await for • A closure is
asynchronous operations. created when a
• Simplifies working with promises. function is
defined within
• Makes asynchronous code look synchronous. another
function,
allowing access
to the outer
function's
variables.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 61 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 62

Functions in JavaScript - Function Parameters Functions in JavaScript - Function Parameters


 Function parameters allow passing values to functions when they are 3. Passing Objects as Parameters: useful for handling multiple named
called. values.
1. Default Parameters: you can assign default values to parameters in
case no arguments are provided.

4. Passing Arrays as Parameters: useful for functions that operate on


2. Rest Parameters (...): used to accept multiple arguments as an array. lists.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 63 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 64
6/30/2025

Functions in JavaScript - Function Parameters JavaScript DOM (Document object Model)


5. Callback Functions as Parameters: is a function that is passed as an
argument to another function and is executed later, usually after  The Document
some operation is completed. This technique is widely used in
Object Model
(DOM) is a tree-like
asynchronous programming, event handling, and higher-order structure that
functions. represents an HTML
document in the
 Why Use Callback Functions? browser.
• To execute a function after another function finishes execution.
• Helps in handling asynchronous operations (e.g., fetching data, reading files).  JavaScript can access
• Enables reusability and modular programming. and manipulate the
DOM to dynamically
change a webpage.
• where each
element is a node.
• we can access,
modify, and
remove nodes

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 65 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 66

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)

 Accessing DOM Elements:  Accessing HTML elements in JavaScript:


• To find specific elements you can use methods like
• [Link]("id") - Select by ID
• [Link]("class-name") - Select
by Class Name
• [Link]("tag-name") - Select by
Tag Name
• [Link]("selector") - Select using first
match
• [Link]("selector") - Select using all
matches

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 67 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 68
6/30/2025

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)

 Navigating the DOM Tree: Using Parent-Child Relationships  Manipulating the DOM:
• parentNode → • Change text content (textContent, innerHTML)
Access the parent
of an element • Modify attributes (setAttribute, removeAttribute)
• childNodes → Get • Change styles ([Link] = "red";)
all child nodes
(including text and • Add and remove elements dynamically (createElement()
elements) and appendChild(), removeChild().)
• firstChild / • Event handling (addEventListener)
lastChild → Get
the first/last child
• nextSibling /
previousSibling →
Move between
sibling elements

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 69 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 70

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)

 Manipulating the DOM:  Manipulating the DOM:


• Changing Content and Attributes, Modifying CSS Styles • Adding & Removing Elements
o Modifying Text Content o Creating and Adding an Element

o Changing Attributes

o Modifying CSS styles o Removing an Element

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 71 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 72
6/30/2025

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)

 Manipulating the DOM:  Events in JavaScript:


• Class Manipulation • The change in the state of an object is known as an Event. In
o Adding and removing classes html, there are various events which represents that some
activity is performed by the user or by the browser.

• When javascript code is included in HTML, js react over


these events and allow the execution. This process of reacting
o Toggling a Class over the events is called Event Handling. Thus, js handles the
HTML events via Event Handlers.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 73 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 74

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)
 Events in JavaScript: Mouse events  Events in JavaScript: Mouse events
Event Performed Event Handler Description
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over
the element
mouseout onmouseout When the cursor of the mouse leaves an
element
mousedown onmousedown When the mouse button is pressed over the
element
mouseup onmouseup When the mouse button is released over
the element
mousemove onmousemove When the mouse movement takes place.
@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 75 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 76
6/30/2025

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)
 Events in JavaScript: Keyboard events  Events in JavaScript: Keyboard events
Event Performed Event Handler Description
Keydown onkeydown Triggered when the key is pressed
down.
Keyup onkeyup Triggered when the key is released.
keypress onkeypress Triggered when a key is pressed and
produces a character. (This event is
now deprecated and only works on
character keys in some browsers.)

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 77 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 78

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)
 Events in JavaScript: Form events  Events in JavaScript: Form events
Event Event Description
Performed Handler
focus onfocus Triggered when an input field gains focus
submit onsubmit Triggered when a form is submitted. You can
prevent default form submission for validation
or other purposes.
blur onblur Triggered when an input field loses focus
change onchange Triggered when the value of an input or select
element is changed and the element loses
focus.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 79 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 80
6/30/2025

JavaScript DOM (Document object Model) JavaScript DOM (Document object Model)
 Events in JavaScript: Window events  Events in JavaScript: Window events

Event Performed Description


load Triggered when the page has fully loaded, including
all resources like images, stylesheets, etc.
beforeunload Triggered before the page is unloaded. This event is
typically used to warn users that they may lose data
if they navigate away or close the tab.
scroll Triggered when the user scrolls the page.
resize Triggered when the window is resized.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 81 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 82

Form Processing-using JavaScript Form Processing-using JavaScript


 JavaScript empowers you to handle form submissions  Form Processing with JavaScript:
dynamically, enhancing user experience and simplifying data • Validation: Validate user input before submission to prevent
collection. invalid data reaching the server.
• Real-time Feedback: Provide immediate feedback to users for better
 Traditional Form Submission (Without JavaScript): input experience.
• User submits the form, data is sent to the server in an HTTP • Asynchronous Submission: Use AJAX (Asynchronous JavaScript
POST request. and XML) to submit data without full page reload, enhancing
responsiveness.
• Server processes the data and generates a response (e.g.,
webpage). • Client-side Processing: Perform basic data manipulation or
calculations on the client-side before sending data to the server.
• Limited interactivity and validation on the client-side.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 83 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 84
6/30/2025

Form Processing-using JavaScript Form Processing-using JavaScript


 Key Steps:  Key Steps:
1. Select Form Elements: Use methods like getElementById() or 4. Prevent Default Submission: Use [Link]() to stop the
querySelector() to access form elements (input fields, buttons, etc.). default form submission if validation fails or additional processing
2. Attach Event Listeners: Add event listeners (usually for the submit is needed.
event of the form) to capture user interactions. 5. AJAX Submission (Optional): Use AJAX libraries like jQuery or
3. Validation and Processing: Within the event listener function: Fetch API to send data to the server without page reload.
• Access form element values using properties like value.
• Perform validation checks (e.g., presence, format, range) using
conditional statements and appropriate methods.
• Provide error messages or visual feedback to the user.
• Optionally, process data on the client-side (e.g., calculations,
formatting).

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 85 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 86

JavaScript BOM (Browser Object Model) JavaScript BOM (Browser Object Model)
 The Browser Object Model (BOM) allows JavaScript to interact
with the browser window and perform operations like opening
new windows, manipulating the address bar, handling events,
and controlling browser history.

 Unlike the DOM (Document Object Model), which focuses on


modifying webpage content, the BOM controls browser-related
functionalities.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 87 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 88
6/30/2025

JavaScript BOM (Browser Object Model) JavaScript BOM (Browser Object Model)
 Key Components of the BOM:  Key Components of the BOM:
• Window Object: The window object represents the browser • Navigator Object: Offers information about the user's browser and
window and provides access to properties like the operating system, such as
o [Link] (for URL), o [Link] - Used to identify the browser and can be
o [Link] (for navigation history), and used to detect the browser type, version, and platform
o [Link] (for the DOM). o [Link] - Returns the preferred language of the user.
o [Link] - Returns true if the browser is connected to
the internet, false if offline.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 89 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 90

JavaScript BOM (Browser Object Model) JavaScript BOM (Browser Object Model)
 Key Components of the BOM:  Key Components of the BOM:
• Location Object: The location object represents the current page's • Screen Object: Provides details about the user's screen resolution,
URL and allows manipulation with properties like href and color depth, and more.
methods like assign() for loading a new document and reload() for
reloading the current document.

• History Object: Manages the browser's navigation history, enabling


navigation control with methods like
o [Link]() - to go back one page and
o [Link]() - to add a new state to the history

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 91 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 92
6/30/2025

JavaScript BOM (Browser Object Model) JavaScript BOM (Browser Object Model)
 Key Components of the BOM:  Key Components of the BOM:
• Timers in BOM: Used to stop or execute code after a delay or at • Events in BOM: BOM events allow interaction between users and
intervals. the browser.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 93 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 94

JavaScript BOM (Browser Object Model) JavaScript BOM (Browser Object Model)

 JavaScript Cookies  JavaScript Cookies


• Cookies are small pieces of data stored in the user's browser • Set a cookie using [Link] = "key=value".
to remember information across sessions, such as login • Read cookies with [Link].
details, preferences, or tracking data. • Delete a cookie by setting an expiration date in the past.
• Cookie Attributes
Attribute Description
expires Sets expiration date (GMT format).
path Defines the URL path where the cookie is accessible.
domain Specifies the domain allowed to access the cookie.
secure Only sends the cookie over HTTPS.
HttpOnly Prevents JavaScript access to the cookie (server-side
only).

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 95 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 96
6/30/2025

Assignment I
Remaining ES6+ Features & Introduction to React
Students are required to write the assignment by hand in their notebooks.
Once completed, the notebooks will be reviewed, and marks will be given if necessary.

 Destructuring Assignment – Extracting values from arrays/objects.


 Modules (import/export) – Using modular JavaScript.
 Promises & Async/Await – Handling asynchronous operations.
 Map, Filter, Reduce – Functional programming methods in arrays.
 Optional Chaining (?.) – Safe property access in objects. Thank You!!!
 What is React? – Why React is popular in front-end development.
 JSX (JavaScript XML) – Writing HTML-like syntax inside JavaScript.
 React Components – Functional vs. Class Components. Question???
 Props & State – Passing data and managing component state.
 Handling Events in React – Using event handlers like onClick.
 React Hooks (useState, useEffect) – Basic usage of hooks.
 React Rendering & Virtual DOM – Understanding how React optimizes
performance.

@ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024 @ WDU: WIT: SCHOOL OF COMPUTING: PROGRAMMING CHAIR 2024
WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 97 WEB PROGRAMMING: CHAPTER 4 (JAVASCRIPT) 98

You might also like