First Script Tag Exercise
First Script Tag Exercise
the Web
🌟 What it is:
A computer is an electronic machine that can receive input, process it, store information,
and produce output, following a set of instructions called a program.
Understanding what a computer really is gives you confidence to work with it — it’s just a tool!
🔍 Basic Explanation:
Imagine a computer as a magical assistant.
You tell it exactly what to do (through programs), and it does it — no more, no less.
It has:
✅ A “body” — the hardware.
✅ A “mind” — the software.
1
🌟 What it is:
● Hardware: the physical parts you can touch — like the monitor, keyboard, and internal
circuits.
● Software: the invisible instructions (programs) that tell the hardware what to do.
Examples:
Hardware Software
CPU Operating
(processor) system
Best analogy:
🧍 Hardware is like your body; software is like your thoughts.
Example:
2
● You press a key (input) → Computer understands it (process) → Letter
appears on screen (output).
● Storage (Disk): Long-term memory. Slower but permanent, like a notebook you can
save things in.
Analogy:
● RAM = your short-term brain (what you’re thinking about right now).
● Disk = your notebook (where you write things you don’t want to forget).
📋 Simple Example:
You draw a picture on a computer:
3
● Input: You move the mouse and click.
🚨 Common Pitfalls:
● Thinking computers are “smart.” They only do what you tell them — even if it’s wrong.
💡 Best Practices:
● Keep hardware clean and avoid overheating.
🔗 References:
● What is a Computer? — Britannica
4
🎯 Exercises:
1️⃣Name two pieces of hardware and two pieces of software you use daily.
2️⃣Draw the Input → Process → Output cycle on paper.
3️⃣Is RAM long-term or short-term memory? Explain.
4️⃣Can you touch software? Why or why not?
5️⃣List three basic operations computers can perform.
Mini Project:
“My Computer at Home or School”
● Write 2–3 sentences about what software you use most and what it helps you do.
📋 Quiz:
✅ Which of these is NOT a hardware component?
● A) CPU
● B) Monitor
● C) Windows
● D) Keyboard
● A) RAM
● B) Hard Disk
● C) Processor
● D) Mouse
5
● A) The computer eats and sleeps
🌟 What it is:
The Internet is a giant network that connects millions of computers and devices all over the
world, allowing them to talk to each other and share information.
🔍 Basic Explanation:
Think of the Internet as a huge spider web where each computer is a point in the web, and all
points are connected by invisible strings.
6
📄 Subtopic: The concept of a network
🌟 What it is:
A network is when two or more computers are connected so they can share information.
Types of networks:
● Small network: Like computers at home or school.
Analogy:
Like a group of friends passing notes to each other in class — each person (computer) can
send or receive notes (data).
Example:
You type a message → Your computer sends it as packets → Friend’s computer
receives and shows the message.
7
● Client: Your computer or phone that requests information from a server.
Example:
You (client) ask for a web page → The server finds it and sends it to you.
Analogy:
Like ordering food at a restaurant:
Example:
You type [Link] → DNS finds its IP address → Your computer connects to that IP
and loads the site.
📋 Simple Example:
● You open your browser → Type [Link] → Browser finds the server →
Server sends the page → You see it.
8
● Watching a YouTube video:
Your computer requests many video data packets → Server streams them →
Your computer plays the video smoothly.
🚨 Common Pitfalls:
● Thinking the Internet and the web are the same.
(The web is just one part of the Internet.)
● Believing data “magically appears” — it’s actually sent through real wires, satellites, and
servers.
💡 Best Practices:
● Protect your personal data while online.
🔗 References:
● What is the Internet? — Britannica
🎯 Exercises:
Mini Project:
9
“My Internet Map”
Draw a map showing:
● Your computer
● The server
📋 Quiz:
✅ The Internet is:
● A) A single computer
● C) Just a browser
● D) A TV channel
✅ A server is:
● A) Your phone
● C) A program
● D) The keyboard
10
📘 Part 1 — Getting Started: Foundations of Computing &
the Web
🌟 What it is:
A web browser is a program on your computer or phone that lets you visit
websites on the Internet.
It knows how to talk to servers, fetch web pages, and display them nicely
for you to read and interact with.
● It makes sense of all the code (HTML, CSS, JavaScript) and shows it
as a page.
🔍 Basic Explanation:
11
Popular browsers:
🌐 Google Chrome, 🦊 Firefox, 🧭 Safari, 🪟 Edge.
🌟 What it is:
12
At the top of your browser is the address bar, where you type the website
you want to visit.
Parts of a URL:
📋 Simple Example:
13
● Server sends the /about page.
🚨 Common Pitfalls:
● Confusing search box and address bar (they look similar but behave
differently).
● Thinking the browser is “the Internet” — it’s just a tool to use the
Internet.
💡 Best Practices:
🔗 References:
🎯 Exercises:
14
1️⃣Name two browsers you’ve heard of or used.
2️⃣What does the browser do when you type a URL?
3️⃣Break down this URL into its parts:
[Link]
4️⃣Why is https:// better than [Link]
5️⃣What happens if you mistype the domain name?
Mini Project:
○ Address bar
○ Tabs
○ Back/forward buttons
○ Bookmarks
📋 Quiz:
● B) A type of server
15
● D) A piece of hardware
● A) Watch videos
● D) Open a file
✅ A URL is:
● A) A computer language
● C) A browser
● D) A server
🌟 What it is:
16
📝 Why it’s important:
● Every web page starts with HTML — it’s the foundation of the page.
🔍 Basic Explanation:
● Head: Contains information about the page (like its title, styles,
scripts).
📋 Example:
<!DOCTYPE html>
17
<html>
<head>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Examples of tags:
Tag Meaning
<h1 Main
> heading
18
<p> Paragraph
<im Image
g>
<a> Link
🌟 Attributes:
Example:
Here:
● src is the attribute that tells the browser where the image is.
🌟 Elements:
Example:
<p>This is a paragraph.</p>
19
📄 Subtopic: A tiny taste — writing your first simple page
Here is a complete, super simple page you can try:
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome to My Page!</h1>
</body>
</html>
🚨 Common Pitfalls:
20
✅ <p>This is a paragraph.</p>
💡 Best Practices:
🔗 References:
🎯 Exercises:
21
4️⃣Try removing the </p> tag and see what happens.
5️⃣Add more headings: <h1>, <h2>, <h3>.
Mini Project:
📋 Quiz:
● A) <head>
● B) <body>
22
● C) <html>
● D) <!DOCTYPE html>
● D) Deletes a tag
🌟 What it is:
● Without CSS, all web pages would look boring — just black text on a
white background.
23
● CSS makes your site beautiful and easy to read.
● You can change the entire look of your site by editing just your CSS.
🔍 Basic Explanation:
🌟 Colors:
● You can set the text color, background color, borders, and shadows.
Example:
p{
color: blue;
background-color: yellow;
🌟 Layouts:
24
● CSS decides how things are arranged: side by side, stacked,
centered, etc.
● You can even make the page look good on phones and tablets
(responsive design).
✅ Internal CSS — style written inside the <style> tag in the <head>.
<head>
<style>
p{
font-size: 20px;
</style>
</head>
25
In [Link]:
body {
background-color: lightgray;
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
h1 {
color: white;
text-align: center;
p{
26
font-size: 20px;
</style>
</head>
<body>
</body>
</html>
🚨 Common Pitfalls:
27
💡 Best Practices:
🔗 References:
🎯 Exercises:
Mini Project:
28
● Make it look nice and easy to read.
📋 Quiz:
● A) Inline
● B) Internal
● C) External
● C) Both A and B
29
📄 Topic 7: What is JavaScript?
🌟 What it is:
JavaScript (JS) is a programming language that lets you make your web
page interactive and alive.
It runs inside the browser, and it’s what makes things happen when you
click, type, scroll, or move your mouse.
● But JavaScript gives life 🕺 — it allows the page to react to what you
do.
Without JavaScript, web pages would just sit there and do nothing.
🔍 Basic Explanation:
Whenever you:
✅ Click a button to submit a form.
✅ See a pop-up message.
✅ Watch an animation happen on a web page.
30
✅ Play a game in your browser.
That’s JavaScript working behind the scenes!
📋 Example:
Without JS:
● The goal was to make web pages smarter — more than just text and
pictures.
Why it exists:
✅ To make web pages dynamic.
✅ To handle user input and respond instantly.
✅ To connect to servers without reloading the page.
✅ To create rich web applications (like Google Docs, YouTube).
Technol Role
ogy
31
HTML The skeleton 🦴 — structure of the
page
📋 Example:
<!DOCTYPE html>
<html>
<head>
<style>
button {
font-size: 20px;
padding: 10px;
</style>
32
</head>
<body>
</body>
</html>
🚨 Common Pitfalls:
💡 Best Practices:
● Learn how to wait until the page is loaded before running scripts.
33
🔗 References:
🎯 Exercises:
Mini Project:
○ A heading: “Welcome!”
34
○ When the button is clicked, show a pop-up that says: “Hello,
World!”
📋 Quiz:
● A) Tim Berners-Lee
● B) Brendan Eich
● C) Bill Gates
● D) Mark Zuckerberg
35
📘 Part 3 — Setting Up for Success
🌟 What it is:
Before you start writing JavaScript seriously, you need some tools — just
like a painter needs brushes, or a chef needs knives.
Here we’ll learn what tools you need to write, test, and see your code
work.
🌟 Recommended Editors:
✅ Notepad
36
● Highlights your code in colors to make it easy to read.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
VS Code will show different colors for tags, text, and attributes — much
easier to read than plain Notepad.
37
🚨 Tip:
But every browser also comes with hidden tools called DevTools
(Developer Tools) — these help you:
🌟 Popular Browsers:
✅ Google Chrome
✅ Mozilla Firefox
✅ Microsoft Edge
To open DevTools:
● Or press F12.
38
[Link]("Hello from the console!");
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
39
3️⃣Save the file as [Link].
4️⃣In the same folder, create a new file called [Link].
5️⃣In [Link], write:
🚨 Common Mistakes:
💡 Best Practices:
my-project/
[Link]
[Link]
40
[Link]
🔗 References:
● Download VS Code
🎯 Exercises:
Mini Project:
“Hello Tools”
41
📋 Quiz:
✅ What is VS Code?
● A) A browser
● B) A text editor
● C) A programming language
● D) A video game
● A) To watch YouTube
● D) To print documents
● A) .html
● B) .txt
● C) .js
● D) .css
42
📄 Topic 9: Where & How to Run
JavaScript
🌟 What it is:
Now that you know what JavaScript is and how to write it, the next big
question is:
Where do you actually run it to see it working?
JavaScript can run:
✅ In your browser (most common).
✅ In a .js file linked to your web page.
✅ Directly in the browser’s console.
✅ Outside the browser (optional: using [Link]).
● If you don’t know where to run your code, you can’t test it!
● Some ways are good for quick testing, others are better for real
projects.
Every browser has a console, where you can write and run JavaScript
instantly — like a playground for code.
43
✅ In Chrome or Firefox:
📋 Example:
You’ll see:
2+2
Result:
44
🌟 What is a script tag?
A <script> tag lets you write JavaScript inside your HTML page.
📋 Example:
<!DOCTYPE html>
<html>
<body>
<h1>My Page</h1>
<script>
</script>
</body>
</html>
45
✅ Keeps your HTML clean.
✅ Easier to organize and maintain.
✅ You can reuse the same .js file on multiple pages.
📋 Example:
In HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My Page</h1>
<script src="[Link]"></script>
</body>
</html>
In [Link]:
46
✅ [Link] lets you run JavaScript outside the browser, directly on
your computer.
✅ Useful for advanced stuff, like making servers or running tools.
✅ Not needed for beginners — focus on the browser first!
● Type:
node
Then type:
🚨 Common Mistakes:
💡 Best Practices:
47
● Use <script> in HTML only for small things.
● Keep .js files in the same folder as your HTML when starting.
🔗 References:
🎯 Exercises:
Mini Project:
○ [Link]
48
○ [Link]
📋 Quiz:
● A) Writing it on paper
● C) Sending it to a friend
● D) Writing it in CSS
● B) To reuse code
● C) To organize better
49
● B) Make websites pretty
● C) Write HTML
🌟 What it is:
50
📋 Syntax:
🚀 Example:
📋 Example:
if (true) {
51
let y = 20; // only exists inside this block
[Link](x); // ✅ works
[Link](y); // ✅ works
[Link](x); // ✅ works
🚨 Lifetime:
let count = 0;
52
📄 Advanced Example:
const MAX_USERS = 100;
❌ Don’t use var unless you have to — it ignores block scope and
can cause bugs.
✅ Always prefer let or const.
✅ Use const whenever possible — it makes your code safer.
✅ Use meaningful names (let x = 1 → bad, let userCount = 1
→ good).
🔗 References:
● let — MDN
● const — MDN
● var — MDN
53
🎯 Exercises:
Mini Project:
“Profile Card”
📋 Quiz:
● A) const
● B) let
54
● C) rock
● D) fix
● A) var
● B) let
● C) const
● D) box
🌟 What it is:
In JavaScript, data types are the kinds of values you can store in
variables.
For example: a number (like 5), a word (like "hello"), or something more
complex (like an object).
55
JavaScript is dynamically typed, which means you don’t have to say the
type when declaring — the computer figures it out.
2️⃣Strings
56
✅ You can join (concatenate) strings:
3️⃣Booleans
4️⃣null
5️⃣undefined
let score;
57
[Link](score); // undefined
6️⃣Symbol (Advanced)
let id = Symbol("id");
7️⃣BigInt (Advanced)
For very large numbers beyond what normal numbers can hold.
Example:
✅ Object example:
let person = {
name: "Alice",
age: 10
58
};
✅ Array example:
typeof 42 // "number"
59
📄 Advanced Example:
let user = {
id: Symbol("id"),
name: "Bob",
age: 25,
isActive: true,
score: null
};
🔗 References:
● typeof — MDN
60
🎯 Exercises:
Mini Project:
“My Profile”
Example:
let profile = {
name: "Alice",
age: 10,
isStudent: true,
};
61
[Link](profile);
📋 Quiz:
● A) number
● B) string
● C) balloon
● D) boolean
● A) "null"
● B) "object"
● C) "undefined"
● D) "nothing"
● A) number
● B) boolean
● C) string
● D) symbol
62
📘 Part 4 — Core JavaScript: The Language
🌟 What it is:
📄 Categories of Operators
1️⃣Arithmetic Operators
63
+ Add 5 + 2
→ 7
- Subtract 5 - 2
→ 3
* Multiply 5 * 2
→ 10
/ Divide 10 / 2
→ 5
% Remainder 5 % 2
→ 1
** Exponentiat 2 ** 3
ion → 8
++ Increment x++ →
x+1
-- Decrement x-- →
x-1
2️⃣Assignment Operators
64
Operat Examp Meaning
or le
= x = 5 assign 5
to x
+= x += x=x+2
2
-= x -= x=x-2
2
*= x *= x=x*2
2
/= x /= x=x/2
2
%= x %= x=x%2
2
3️⃣Comparison Operators
65
== 5 == true
"5"
!= 5 != true
3
4️⃣Logical Operators
66
&& AND true && true
→ true
5️⃣Ternary Operator
✅ Example:
[Link](canVote); // "No"
🚀 Simple Example:
let x = 10;
x += 5; // 15
[Link](x);
67
[Link](10 > 5); // true
🌟 Advanced Example:
let a = 5;
let b = "5";
[Link](grade); // Pass
68
🚨 Potential Pitfalls & Best Practices:
🔗 References:
● Operators — MDN
🎯 Exercises:
Mini Project:
69
● If age >= 60 → “Senior ticket: $7”.
● Use if/else or ternary operators to determine the message and log it.
📋 Quiz:
● A) ==
● B) =
● C) ===
● D) !=
● A) &&
● B) ||
● C) !
● D) !==
● A) true
● B) false
● C) error
● D) undefined
70
📘 Part 4 — Core JavaScript: The Language
🌟 What it is:
Control flow means the order in which the computer runs your code.
You don’t always want your program to run line by line — sometimes you
want to make choices (if), repeat actions (loops), or stop early.
🔷 Conditional Statements
These let your code decide which path to take based on some condition.
1️⃣if…else
71
if (age >= 18) {
} else {
2️⃣else if
[Link]("A grade");
[Link]("B grade");
} else {
[Link]("C grade");
3️⃣switch…case
72
✅ Another way to handle multiple choices.
✅ Often cleaner than many if…else if…else.
let day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Other day");
🚨 Don’t forget the break; — without it, code continues to the next case!
🔷 Loops
These let you repeat actions automatically.
73
4️⃣for loop
5️⃣while loop
let count = 1;
count++;
6️⃣do…while loop
let num = 5;
74
do {
num--;
if (i === 3) continue;
if (i === 4) break;
[Link](i);
// Outputs: 1, 2
🚀 Simple Example:
75
let fruit = "apple";
[Link]("Yum!");
} else {
[Link]("Not an apple.");
🌟 Advanced Example:
continue;
76
}
🔗 References:
● if…else — MDN
● switch — MDN
● loops — MDN
🎯 Exercises:
Mini Project:
77
● Pick a secret number (e.g., 7).
let secret = 7;
let guess = 5;
[Link]("Too high");
[Link]("Too low");
} else {
📋 Quiz:
● A) for
● B) while
78
● C) do…while
● D) break
● A) continue
● B) stop
● C) break
● D) exit
● A) Error
● D) Nothing happens
🌟 What it is:
79
📝 Why it’s important:
📄 Parts of a Function
1️⃣Function Declaration
function greet() {
[Link]("Hello!");
You can make functions more flexible by giving them parameters — inputs
that change what the function does.
function greet(name) {
80
greet("Alice"); // Output: Hello, Alice!
function add(a, b) {
return a + b;
[Link](sum); // Output: 5
Traditional Declaration
function sayHi() {
[Link]("Hi!");
81
Function Expression
[Link]("Hi!");
};
sayHi();
[Link]("Hi!");
};
sayHi();
[Link](square(4)); // Output: 16
Anonymous Functions
82
setTimeout(function() {
}, 1000);
🚀 Simple Example:
function multiply(x, y) {
[Link](x * y);
🌟 Advanced Example:
const operations = [
function(x) { return x + 1; },
function(x) { return x * 2; },
83
x => x ** 2
];
let result = 5;
result = op(result);
🔗 References:
● Functions — MDN
🎯 Exercises:
84
3️⃣Write an arrow function that doubles a number.
4️⃣Write a function that takes a number and prints “Even” if even, or
“Odd” if odd.
5️⃣Write a function that greets someone differently if they are a kid,
adult, or senior.
Mini Project:
“Simple Calculator”
switch(operator) {
85
}
[Link](calculate(4, 2, "+")); // 6
📋 Quiz:
● A) func
● B) function
● C) def
● D) declare
● A) 0
● B) null
● C) undefined
● D) false
● A) sayHello;
● B) call sayHello;
● C) sayHello();
86
● D) sayHello{};
🌟 What it is:
✅ Helps you keep your variables safe from other parts of the
code.
✅ Makes your code predictable and less buggy.
✅ Allows you to create powerful patterns, like hiding data
(encapsulation).
Types of Scope
1 Global Scope
1️⃣
87
function show() {
[Link](globalVar);
function greet() {
[Link](message);
if (true) {
[Link](blockVar);
88
}
// [Link](blockVar); ❌ Error
Scope Chain
function inner() {
[Link](outer);
What is a Closure?
Simple Example:
89
function outer() {
let count = 0;
function inner() {
count++;
[Link](count);
return inner;
counter(); // Output: 1
counter(); // Output: 2
90
🌟 Advanced Example:
function createSecret(secret) {
return function() {
};
🔗 References:
● Scope — MDN
● Closures — MDN
🎯 Exercises:
91
1️⃣Write a function that declares a variable inside and prints it.
2️⃣Write a block with let and try to access the variable outside — what
happens?
3️⃣Create a function that returns another function which adds 1 each time
you call it.
4️⃣Write a closure that stores a secret number and only reveals it when
called.
Mini Project:
“Counter Factory”
function createCounter() {
let count = 0;
return {
};
92
[Link]();
[Link]([Link]()); // Output: 1
📋 Quiz:
● A) Global
● B) Local
● C) Universal
● D) Static
● A) Error
● B) Becomes global
● C) Private
● D) Deleted
● D) Nothing
93
📘 Part 4 — Core JavaScript: The Language
🌟 What it is:
Variables
[Link](x);
var x = 5;
var x;
94
[Link](x); // undefined
x = 5;
Functions
➡️Function declarations are fully hoisted — both their name and their body.
sayHi();
function sayHi() {
[Link]("Hi!");
✅ Output:
Hi!
➡️let and const are hoisted, but they are in a “temporal dead zone” (TDZ)
until the line where they are declared.
➡️You can’t use them before the declaration line.
[Link](a); // ❌ ReferenceError
let a = 10;
95
📄 Examples
[Link](name); // undefined
[Link](name); // Alice
[Link](age); // ❌ ReferenceError
greet();
function greet() {
[Link]("Hello!");
96
✅ Works fine because the whole function is hoisted.
greet(); // ❌ TypeError
[Link]("Hi!");
};
🔗 References:
97
● Hoisting — MDN
🎯 Exercises:
[Link](a);
var a = 10;
[Link](b);
let b = 20;
Mini Project:
“Hoist Checker”
● Write a small program where you declare a few variables (var, let,
const) and functions.
98
📋 Quiz:
● A) Ignores them
● B) Deletes them
● A) 0
● B) undefined
● C) null
● D) Error
● A) No
99
📄 Topic 17: The this keyword
🌟 What it is:
🔷 In Global Context
[Link](this);
100
🔷 Inside a Function
✅ Regular function:
function showThis() {
[Link](this);
showThis();
✅ In strict mode:
"use strict";
function showThisStrict() {
[Link](this);
showThisStrict();
// Output: undefined
🔷 Inside a Method
const person = {
101
name: "Alice",
greet: function () {
};
[Link]();
When you use new, this refers to the newly created object.
function Person(name) {
[Link] = name;
[Link]([Link]);
// Output: Bob
🔷 In Arrow Functions
102
Arrow functions don’t have their own this.
They inherit this from the surrounding (outer) scope.
const obj = {
name: "Carol",
greet: function () {
[Link]([Link]);
};
arrow();
};
[Link]();
// Output: Carol
🔷 In Event Handlers
✅ Regular function:
[Link]("button").addEventListener("click", function () {
[Link](this);
});
103
✅ Arrow function:
[Link]("button").addEventListener("click", () => {
[Link](this);
});
call()
function greet() {
[Link]([Link]);
[Link](person);
// Output: Dave
apply()
104
function greet(greeting) {
[Link](person, ["Hi"]);
bind()
greetPerson();
105
✅ Always check what is calling the function to know what this will be.
✅ Use bind() when passing methods as callbacks if needed.
🔗 References:
● this — MDN
● call/apply/bind — MDN
🎯 Exercises:
Mini Project:
“Who Am I?”
const animal = {
type: "Dog",
describe: function () {
106
}
};
setTimeout([Link](animal), 1000);
📋 Quiz:
● A) window
● B) undefined
● D) null
● A) A new function
● C) undefined
● D) null
● A) Yes
107
● B) No
🌟 What it is:
An array is a special type of object in JavaScript that can store a list of values
(called elements) in a single variable.
Think of it as a row of boxes, where each box has a number (index) and holds a
value.
[Link](fruits);
108
[Link](numbers);
Empty array
Index starts at 0
[Link](colors[0]); // red
[Link](colors[2]); // blue
Change a value
colors[1] = "yellow";
[Link](colors);
🔷 Adding elements
109
const arr = [1, 2];
[Link](arr);
// [0, 1, 2, 3]
🔷 Removing elements
[Link](arr);
// [1, 2]
🔷 Finding elements
[Link]([Link](2)); // 1
[Link]([Link](3)); // false
🔷 Iterating
[Link](function (item) {
[Link](item);
});
110
📄 More Useful Methods
[Link](doubled);
[Link](even);
[Link](sum);
[Link](part);
[Link](arr);
111
📄 Real-World Use Cases:
✅ Storing a list of users, products, or messages.
✅ Looping through data and rendering it on a web page.
✅ Transforming and filtering data from an API.
🔗 References:
● Arrays — MDN
🎯 Exercises:
Mini Project:
“Shopping List”
112
● Create an array called shoppingList with 5 items.
📋 Quiz:
● A) 1
● B) 0
● C) -1
● D) None
● A) shift
● B) pop
● C) push
● D) unshift
● A) splice
● B) filter
113
● C) pop
● D) shift
🌟 What it is:
114
All three ways work, but backticks (`) are special — they let you embed variables
and create multiline strings.
Strings are made of individual characters, and you can access them using
indices.
➡️Index starts at 0 (just like arrays).
➡️Negative indices do not work directly in JS (use .slice() for that).
[Link](greeting[0]); // H
[Link](greeting[4]); // o
[Link](greeting[10]); // undefined
● Newline: \n
● Tab: \t
115
const text = "Line1\nLine2";
[Link](text);
Output:
Line1
Line2
🔷 Length of a string
[Link]([Link]);
// 10
🔷 Changing Case
[Link]([Link]()); // ALICE
[Link]([Link]()); // alice
116
🔷 Searching & Checking
[Link]([Link]("love")); // 2
[Link]([Link]("a")); // 13
[Link]([Link]("Java")); // true
[Link]([Link]("I")); // true
[Link]([Link]("t")); // true
[Link]([Link](-6)); // Script
🔷 Replace
[Link]([Link]("cats", "dogs"));
117
// I like dogs
[Link]([Link]()); // hello
[Link]([Link](3)); // hahaha
📄 Template Literals
118
Template literals (backticks) allow:
✅ Variables inside strings.
✅ Multiline strings.
Welcome to JavaScript.`;
[Link](message);
word[0] = "B";
119
🔗 References:
● Strings — MDN
🎯 Exercises:
1️⃣Create a string variable with your favorite quote and print it.
2️⃣Print the length of the string.
3️⃣Access the first and last characters using indexing.
4️⃣Convert it to all uppercase, then all lowercase.
5️⃣Check if the string contains a specific word using .includes().
6️⃣Replace a word in the string with another word.
7️⃣Trim a string with extra spaces and print it.
8️⃣Split a sentence into words and join them with -.
Mini Project:
“Personal Introduction”
○ “Hi, my name is NAME. I’m AGE years old and I love HOBBY.”
120
const intro = `Hi, my name is ${name}. I'm ${age} years old and I love ${hobby}.`;
[Link](intro);
📋 Quiz:
● A) hello
● B) HELLO
● C) Error
● D) undefined
● A) Double quotes
● B) Single quotes
● C) Template literals
● D) None
121
📘 Part 5 — Working With Data
🌟 What it is:
For example:
🚗 Car
🔷 Object Literal
const person = {
name: "Alice",
122
age: 12,
hobby: "drawing"
};
[Link](person);
[Link] = "Bob";
[Link] = 10;
[Link](person);
📄 Accessing Properties
🔷 Dot Notation
[Link]([Link]); // Alice
🔷 Bracket Notation
[Link](person["age"]); // 12
123
[Link](person[prop]); // drawing
🔷 Changing existing
[Link] = 13;
🔷 Adding new
[Link] = "Greenwood";
🔷 Deleting properties
delete [Link];
const dog = {
name: "Buddy",
bark: function () {
[Link]("Woof!");
124
}
};
[Link](); // Woof!
Shortcut (ES6):
const cat = {
meow() {
[Link]("Meow!");
};
[Link](); // Meow!
📄 this in Objects
const car = {
brand: "Toyota",
showBrand() {
[Link]([Link]);
125
}
};
[Link](); // Toyota
[Link]([Link](person));
[Link]([Link](person));
[Link]([Link](person));
126
📄 Shorthand & Computed Properties
Shorthand
[Link](student);
const user = {
[key]: "blue"
};
[Link]([Link]); // blue
127
✅ Working with JSON (data from APIs).
✅ Grouping related data & functions together.
🔗 References:
● Objects — MDN
🎯 Exercises:
Mini Project:
“Pet Information”
128
○ name, type, age
const pet = {
name: "Buddy",
type: "dog",
age: 3,
describe() {
};
[Link]();
📋 Quiz:
● A) person(name)
● B) [Link]
129
● C) person->name
● D) person[name]
● A) Sets age to 0
● C) Throws an error
● D) Does nothing
● B) The method
● D) undefined
🌟 What it is:
In JavaScript, prototypes and inheritance are the mechanisms that allow objects to share
behavior and data with each other.
You can think of it like a family tree:
👴 Grandparent → 👨 Parent → 👶 Child.
If a child doesn’t know something, it can “ask” its parent, and if the parent doesn’t know, it asks
the grandparent — that’s the prototype chain.
130
📝 Why it’s important:
✅ Makes JavaScript very powerful and memory-efficient.
✅ Instead of copying methods into every object, objects can inherit from a common
prototype.
✅ Enables code reuse, and it’s the foundation of JavaScript’s object-oriented
programming.
Every JavaScript object has a hidden link to another object called its prototype.
This prototype can also have its own prototype, creating a prototype chain, which ends at
null.
Example:
const person = { name: "Alice" };
[Link](person.__proto__); // Shows the prototype (Object)
Even though you never defined it, person can use methods like .toString() because it
inherits them from [Link].
📄 Creating Prototypes
🔷 [Link]()
const animal = {
speak() {
[Link]("Animal speaks");
}
};
131
[Link] = "Buddy";
[Link](); // Animal speaks
Constructor Functions:
A function used to create objects.
function Person(name) {
[Link] = name;
}
const alice = new Person("Alice");
[Link] = function () {
[Link](`Hi, I’m ${[Link]}`);
};
If JavaScript doesn’t find a property or method on an object, it looks at the prototype, then the
prototype’s prototype, and so on until it reaches null.
132
📄 ES6 Classes: A Friendlier Syntax
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a sound`);
}
}
This is just syntactic sugar — under the hood it still uses prototypes.
🔗 References:
● Prototypes & Inheritance — MDN
133
🎯 Exercises:
1️⃣Create an object animal with a method speak.
2️⃣Create another object that inherits from animal and override speak.
3️⃣Make a constructor function Car with a property brand. Add a method drive() to its
prototype.
4️⃣Use [Link]() to create an object and test prototype behavior.
5️⃣Use class syntax to define a Person with a method greet.
Mini Project:
“Zoo Simulator”
class Animal {
constructor(name, species) {
[Link] = name;
[Link] = species;
}
describe() {
[Link](`I am a ${[Link]} named ${[Link]}.`);
}
}
[Link]();
[Link]();
134
Output:
📋 Quiz:
✅ What is a prototype in JavaScript?
● A) A copy of an object
● D) A variable
● A) [Link]()
● B) [Link]()
● C) [Link]()
● D) [Link]()
class Person {
constructor(name) {
[Link] = name;
}
}
● C) Throws an error
135
● D) Nothing
🌟 What it is:
ES6 (also called ECMAScript 2015) and later versions introduced many modern,
powerful, and cleaner ways to write JavaScript.
These features make code:
✅ Easier to read & write
✅ Safer & more predictable
✅ More expressive & efficient
136
let age = 10;
age = 11; // ✅ okay
🔷 Destructuring
Extract values from arrays or objects into variables.
Array destructuring:
const colors = ["red", "green", "blue"];
const [first, second] = colors;
[Link](first); // red
Object destructuring:
const person = { name: "Alice", age: 12 };
const { name, age } = person;
[Link](age); // 12
137
const obj1 = {a:1};
const obj2 = {...obj1, b:2};
[Link](obj2); // {a:1, b:2}
🔷 Template Literals
Multi-line strings & embedded expressions using backticks (`).
🔷 Arrow Functions
Shorter syntax for functions:
🔷 Classes
Cleaner way to create objects and use inheritance.
class Person {
constructor(name) {
[Link] = name;
}
greet() {
[Link](`Hi, I'm ${[Link]}`);
}
}
138
🔷 Modules (import/export)
Split your code into separate files and reuse them.
// file: [Link]
export function greet(name) {
[Link](`Hello, ${name}`);
}
// file: [Link]
import { greet } from './[Link]';
greet("Alice");
139
🚨 Potential Pitfalls & Best Practices:
❌ Don’t overuse let — prefer const when you don’t need to reassign.
✅ Use template literals instead of messy string concatenation.
✅ Use arrow functions carefully — they don’t bind their own this.
✅ Don’t deeply nest optional chaining — it can hide design flaws.
🔗 References:
● ES6 Guide — MDN
● Modules — MDN
🎯 Exercises:
1️⃣Rewrite a var declaration to use let or const.
2️⃣Destructure an array of three fruits into three variables.
3️⃣Merge two arrays using spread.
4️⃣Write a template literal greeting using a variable.
5️⃣Convert a regular function into an arrow function.
6️⃣Create a Person class and instantiate two people.
7️⃣Write a safe property access using optional chaining.
8️⃣Use ?? to provide a default value.
Mini Project:
“Profile Card”
● Use destructuring and template literals to display their profile in this format:
140
Name: Alice
Age: 12
City: Paris
const user = {
name: "Alice",
age: 12,
city: "Paris"
};
📋 Quiz:
✅ Which of these creates a constant variable?
● A) var
● B) const
● C) let
● D) constant
● A) ... (spread)
● B) ??
● C) ::
● D) **
141
● B) Checks if a property exists before accessing it
● C) Combines arrays
● D) Declares a function
🌟 What it is:
Even the best programs encounter mistakes. Sometimes it’s because the user typed something
wrong, sometimes because the network failed, or even because of a bug in the code.
Error handling in JavaScript is how we gracefully deal with those mistakes instead of letting the
whole program crash.
142
Runtime Error: Something goes wrong while the code is running.
●
● Logical Error: The code runs but does the wrong thing because of a mistake in your
logic.
(These are the trickiest because they don’t throw an error!)
try {
[Link]("Start");
const result = riskyOperation(); // Something risky
[Link]("Result:", result);
} catch (error) {
[Link]("Oops! An error occurred:", [Link]);
}
Start
Oops! An error occurred: riskyOperation is not defined
🔷 finally Block
If you want to run some code whether or not an error occurred, use finally.
try {
riskyOperation();
} catch (error) {
[Link]("Caught:", error);
143
} finally {
[Link]("Cleaning up…");
}
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
[Link](divide(10, 0));
} catch (err) {
[Link]([Link]);
}
Output:
📄 Custom Errors
144
You can create your own error types for specific situations.
try {
throw new ValidationError("Invalid username");
} catch (e) {
[Link]([Link]); // ValidationError
[Link]([Link]); // Invalid username
}
🔗 References:
● Error Handling — MDN
145
🎯 Exercises:
1️⃣Write a try…catch block around code that divides two numbers, catching division by
zero.
2️⃣Throw an error if someone tries to withdraw more money than their bank balance.
3️⃣Create a custom error class called AgeError and throw it if age is less than 18.
4️⃣Write a try…catch…finally block that logs each stage of execution.
5️⃣Catch and log the error if you try to access a property of undefined.
Mini Project:
“Safe Calculator”
try {
[Link](calculate(10, 0, "divide"));
} catch (e) {
[Link]("Error:", [Link]);
}
146
📋 Quiz:
✅ What happens if an error occurs inside a try block?
● B) It jumps to catch
● C) Nothing happens
● D) It jumps to finally
● A) error
● B) catch
● C) throw
● D) raise
● D) Never runs
🌟 What it is:
Iteration means going through each item in a group (like an array or a string) and doing
something with it.
147
In JavaScript, ES6+ introduced some advanced ways of iterating beyond simple for and
while loops.
This topic covers:
✅ Iterables & Iterators
✅ Generators
✅ Promises & async/await (for asynchronous iteration)
These tools give you more control, allow you to handle infinite sequences, and even make
asynchronous operations look synchronous.
📄 What is an Iterable?
● Arrays
● Strings
● Maps
● Sets
Behind the scenes, an iterable has a method called [[Link]]() that produces an
iterator.
📄 What is an Iterator?
An iterator is an object that knows how to step through a sequence.
It has a .next() method which returns:
148
{ value: ..., done: ... }
where:
[Link](num);
🔷 Generators
149
📄 What is a Generator?
A generator is a special kind of function that can pause and resume.
It produces an iterator for you.
yield i;
With for…of:
[Link](num);
150
}
📄 What is a Promise?
A Promise is a placeholder for a value that’s not ready yet (but will be later).
Promises are the modern way to handle asynchronous operations.
Three states:
● Pending
● Fulfilled (resolved)
● Rejected
🔷 Example: Promise
const promise = new Promise((resolve, reject) => {
});
📄 Why Async/Await?
151
🔷 Example: Async/Await
function delay(ms) {
[Link]("Start");
await delay(1000);
run();
🔷 Iterating Asynchronously
Sometimes you need to await each step inside a loop.
✅ Use for…of with await.
await delay(500);
[Link](num);
process();
152
📄 Real-World Use Cases:
✅ Lazy-load a long list of data using generators.
✅ Fetch paginated API data one page at a time.
✅ Wait for each user action before moving to the next step.
✅ Handle streams of data from a server.
🔗 References:
● Iterators & Generators — MDN
● Promises — MDN
● async/await — MDN
🎯 Exercises:
1️⃣Write a for…of loop to print each character in the string "hello".
2️⃣Use an iterator explicitly to print the first 3 numbers of an array.
3️⃣Create a generator that yields the first 5 square numbers.
4️⃣Write a Promise that resolves after 2 seconds and logs a message.
5️⃣Rewrite the Promise from #4 using async/await.
6️⃣Use a generator to produce an infinite sequence of even numbers (but only print first 4).
153
Mini Project:
“Async Counter”
function delay(ms) {
[Link](i);
await delay(1000);
[Link]("Done!");
asyncCounter();
📋 Quiz:
✅ Which of these can pause and resume?
● A) Normal function
● B) Generator
154
● C) Promise
● D) Variable
● D) Creates an iterator
● A) for…in
● B) for…of
● C) while
● D) foreach…in
🌟 What it is:
The DOM (Document Object Model) is how JavaScript sees and interacts with a web page.
When a browser loads a web page, it takes the HTML and builds a tree structure of objects —
this is called the DOM.
155
📝 Why it’s important:
✅ Without the DOM, JavaScript couldn’t interact with the page.
✅ It allows you to create dynamic and interactive web pages.
✅ Almost everything you build for the browser involves the DOM.
🔷 Example:
HTML:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</body>
</html>
DOM Tree:
Document
└── html
├── head
156
└── body
├── h1
└── p
🔷 Examples in JavaScript
Accessing the document:
[Link]([Link]);
157
Accessing the head:
[Link]([Link]);
[Link]("DOM is ready!");
});
🔗 References:
● Introduction to the DOM — MDN
158
🎯 Exercises:
1️⃣Open the browser console and type document. What do you see?
2️⃣Find the <body> element using [Link].
3️⃣Log the text of the first <h1> on a page.
4️⃣Draw the DOM tree for a small HTML snippet.
5️⃣Write code that logs all children of [Link].
Mini Project:
“DOM Explorer”
HTML:
<h1>Welcome!</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
JavaScript:
[Link]([Link]("h1").textContent);
[Link]("p")[1].textContent = "Changed!";
[Link]([Link]);
159
📋 Quiz:
✅ What does DOM stand for?
● A) document
● B) window
● C) body
● D) head
● A) Document Node
● B) Element Node
● C) Text Node
● D) Function Node
🌟 What it is:
To change or interact with elements on a web page, you first need to find (select) them in the
DOM.
160
JavaScript gives you several methods to select elements in the DOM tree, so you can read or
modify them.
1️⃣getElementById(id)
2️⃣getElementsByTagName(tagName)
161
● 🪞 Returns a live HTMLCollection (not a real array).
<p>Para 1</p>
<p>Para 2</p>
[Link](paragraphs[0].textContent); // Para 1
3️⃣getElementsByClassName(className)
[Link]([Link]); // 2
4️⃣querySelector(selector)
<p class="note">Important</p>
162
[Link]([Link]); // Important
5️⃣querySelectorAll(selector)
<p class="note">One</p>
<p class="note">Two</p>
🔷 Comparing Methods
Method Returns Best for
163
querySelector First matching Element Flexible single selection
🔗 References:
● [Link] — MDN
● [Link] — MDN
● [Link] — MDN
🎯 Exercises:
1️⃣Use getElementById to get a heading and change its text.
2️⃣Use getElementsByTagName to log all paragraph texts.
164
3️⃣Use getElementsByClassName to count how many .item elements exist.
4️⃣Use querySelector to find the first .note element and style it.
5️⃣Use querySelectorAll to add a blue class to every .link.
Mini Project:
“Dynamic List Highlighter”
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
if (index % 2 === 0) {
[Link] = "#f0f0f0";
[Link]("click", () => {
[Link] = "yellow";
});
165
});
📋 Quiz:
✅ Which method always returns exactly one element?
● A) getElementsByTagName
● B) querySelectorAll
● C) getElementById
● D) getElementsByClassName
● A) querySelectorAll
● B) getElementsByClassName
● C) querySelector
● D) [Link]
● A) getElementById
● B) querySelector
● C) getElementsByTagName
● D) getElementsByClassName
166
🌟 What it is:
After selecting elements in the DOM, you can change them — their text, HTML, styles,
attributes, or even add and remove elements.
This is what makes your web pages dynamic and interactive instead of static.
🔷 Examples:
167
<h1 id="heading">Hello</h1>
// Change text
// Add HTML
📄 Modifying Styles
You can change styles inline using the .style property.
<p id="para">Paragraph</p>
[Link] = "blue";
[Link] = "lightgray";
[Link] = "20px";
🔷 Best Practice:
Instead of writing a lot of inline styles, add or remove classes using:
● [Link]()
● [Link]()
168
● [Link]()
[Link]("highlight");
[Link]("hidden");
[Link]("active");
● getAttribute(name)
● setAttribute(name, value)
● removeAttribute(name)
// Change href
[Link]("href", "[Link]
// Read href
[Link]([Link]("href"));
// Remove href
[Link]("href");
169
📄 Adding Elements
You can create and insert new elements with:
● [Link](tagName)
● [Link](child)
● [Link](newNode, referenceNode)
● [Link](position, htmlString)
[Link](newPara);
📄 Removing Elements
You can remove an element with:
● [Link](child)
● Or .remove() (modern)
[Link]();
170
🚨 Potential Pitfalls & Best Practices:
❌ Avoid heavy DOM changes inside loops (use DocumentFragment for batches).
✅ Use classList for styling rather than inline .style.
✅ Sanitize user input before inserting it with innerHTML (to prevent XSS).
🔗 References:
● textContent — MDN
● innerHTML — MDN
● [Link] — MDN
● createElement — MDN
🎯 Exercises:
1️⃣Change the text of an <h1> to your name.
2️⃣Make a paragraph text blue and bold using .style.
3️⃣Add a new <li> to an existing list dynamically.
4️⃣Toggle a class on a button when it’s clicked.
5️⃣Remove an image from the page when a link is clicked.
Mini Project:
“Interactive To-Do List”
171
○ Adds a new <li> with the input text when button is clicked.
<button>Add</button>
<ul id="list"></ul>
[Link]("click", () => {
const li = [Link]("li");
[Link] = [Link];
[Link](li);
[Link] = "";
});
📋 Quiz:
✅ Which property is used to change the text inside an element?
● A) .value
● B) .textContent
● C) .innerElement
172
● D) .htmlText
● A) .[Link]()
● B) .removeClass()
● C) .[Link]()
● D) .className()
● A) .newElement()
● B) [Link]()
● C) .create()
● D) [Link]()
🌟 What it is:
An event is something that happens on your web page — like a user clicking a button, moving
their mouse, pressing a key, submitting a form, etc.
JavaScript lets you listen for these events and then run code when they happen.
This is how you make web pages interactive.
173
🔷 How to Listen to Events
You use event listeners to listen for specific events on specific elements.
📄 addEventListener()
Syntax:
[Link](eventType, callbackFunction);
Example:
<button id="btn">Click me</button>
[Link]("click", () => {
alert("Button clicked!");
});
174
Event Type When it Happens
🔷 Event Object
When an event happens, JavaScript passes an event object to your function with information
about the event.
175
[Link]([Link]); // click
});
function handleClick() {
alert("Clicked!");
[Link]("click", handleClick);
[Link]("click", handleClick);
🔷 Event Propagation
Events don’t just affect the element you clicked on — they can also bubble up through parent
elements or even capture events on the way down.
📄 Bubbling vs Capturing:
● Bubbling (default): The event happens on the element, then moves up to its parents.
● Capturing: The event starts from the top of the DOM tree and moves down to the
target.
You can specify which phase with the third argument in addEventListener.
176
Example:
<div id="outer">
</div>
[Link]("outer").addEventListener("click", () => {
[Link]("Outer clicked!");
});
[Link]("inner").addEventListener("click", () => {
[Link]("Inner clicked!");
});
Inner clicked!
Outer clicked!
🔷 Event Delegation
Instead of adding a separate listener to each child element, you can put one listener on a parent
and check which child triggered the event.
Example:
[Link]("list").addEventListener("click", (e) => {
177
[Link](`You clicked: ${[Link]}`);
});
🔗 References:
● addEventListener — MDN
🎯 Exercises:
1️⃣Add a click event to a button that changes its color.
2️⃣Make a div turn red when the mouse hovers over it and back to white when it leaves.
178
3️⃣Create a form that shows an alert when submitted.
4️⃣Log each key the user presses in an input box.
5️⃣Add one listener to a <ul> that logs which <li> was clicked.
Mini Project:
“Interactive Counter”
● JavaScript:
<h1 id="count">0</h1>
<button id="inc">+</button>
<button id="dec">-</button>
[Link]("click", () => {
[Link] = +[Link] + 1;
});
[Link]("click", () => {
[Link] = +[Link] - 1;
179
});
📋 Quiz:
✅ Which method is used to listen for an event?
● A) .onEvent()
● B) .listen()
● C) .addEventListener()
● D) .handleEvent()
● B) To prevent events.
180
🌟 What it is:
A form on a webpage lets users enter information — like their name, email,
password — and send it to you.
JavaScript helps you:
✅ Read what the user typed.
✅ Check if it’s correct (validate).
✅ Prevent sending bad data.
✅ Do something with the data without reloading the page.
181
📄 Reading Form Data
You access form inputs using the DOM:
<form id="myForm">
<button>Submit</button>
</form>
[Link]([Link]);
});
Example:
182
[Link]("submit", (e) => {
[Link]();
} else {
alert(`Hello, ${name}`);
});
🔷 Common Validations:
✅ Required fields (not empty)
✅ Correct email format
✅ Password length & complexity
✅ Matching passwords
✅ Number within a range
[Link]();
183
✅ Sign-up and login forms.
✅ Search bars that show results immediately.
✅ Feedback forms that check for empty fields.
✅ Online surveys.
🔗 References:
● HTML Forms — MDN
● FormData — MDN
🎯 Exercises:
1️⃣Log the value of a text field when a button is clicked.
2️⃣Prevent form submission & display a message if a field is empty.
3️⃣Show an alert if the password is less than 8 characters.
4️⃣Check if two password fields match before submitting.
5️⃣Read the selected option from a dropdown menu.
Mini Project:
“Simple Login Form”
184
● HTML: 2 inputs (username, password) and a submit button.
● JavaScript:
<form id="login">
<button>Login</button>
</form>
[Link]();
if (![Link] || ![Link]) {
} else {
alert(`Welcome, ${[Link]}!`);
});
185
📋 Quiz:
✅ Which method stops the page from refreshing when submitting a form?
● A) stopPage()
● B) preventDefault()
● C) cancelSubmit()
● D) blockReload()
● A) .text
● B) .value
● C) .input
● D) .content
● B) To confuse users
🌟 What it is:
186
Sometimes you don’t want your code to run immediately — you want it to happen after a
delay, or to repeat over time.
JavaScript provides timing functions to schedule actions at specific intervals.
requestAnimationFr Run code before the next screen repaint (best for
ame() animations).
📄 setTimeout()
Run a function after a delay (in milliseconds).
187
Syntax:
setTimeout(function, delay);
Example:
setTimeout(() => {
}, 2000);
📄 setInterval()
Run a function repeatedly, every delay milliseconds.
Syntax:
setInterval(function, delay);
Example:
setInterval(() => {
}, 1000);
📄 Stopping Timers
Both setTimeout and setInterval return an ID.
You can stop them using clearTimeout() or clearInterval().
Example:
188
const timerId = setTimeout(() => {
}, 3000);
clearTimeout(timerId);
For intervals:
[Link]("Repeating...");
}, 1000);
clearInterval(intervalId);
📄 requestAnimationFrame()
This is the preferred way to make smooth animations, because it synchronizes with the
screen’s refresh rate (~60fps).
Syntax:
requestAnimationFrame(callback);
Example:
function animate() {
[Link]("Frame!");
requestAnimationFrame(animate);
189
requestAnimationFrame(animate);
🔗 References:
● setTimeout — MDN
● setInterval — MDN
● requestAnimationFrame — MDN
🎯 Exercises:
1️⃣Write a setTimeout that logs “Hi!” after 5 seconds.
2️⃣Use setInterval to log the current time every second.
190
3️⃣Make a countdown timer that shows 10 → 0, then says “Time’s up!”.
4️⃣Cancel an interval after 5 repetitions.
5️⃣Use requestAnimationFrame to move a box across the screen smoothly.
Mini Project:
“Digital Clock”
● JavaScript:
<h1 id="clock"></h1>
function updateClock() {
[Link]("clock").textContent = [Link]();
setInterval(updateClock, 1000);
📋 Quiz:
✅ Which function runs code repeatedly?
● A) setTimeout
191
● B) setInterval
● C) requestAnimationFrame
● D) clearInterval
● D) Stops animations.
🌟 What it is:
When a user visits your website, you may want to remember some data — like their
preferences, login state, or a shopping cart — even if they close and reopen the browser.
The browser provides storage mechanisms that let you save small bits of data on the user’s
computer.
192
✅ Makes your site more user-friendly by saving state.
✅ Avoids asking users to repeat information.
✅ Enables offline functionality in some cases.
📄 Cookies
What are they?
● Tiny pieces of data sent to and from the server and stored in the browser.
Example:
[Link] = "username=John; expires=Fri, 31 Dec 2025 [Link] GMT";
[Link]([Link]);
193
⚠️Notes:
📄 localStorage
What is it?
● Stores key/value pairs.
Methods:
Example:
[Link]("theme", "dark");
[Link]([Link]("theme")); // dark
[Link]("theme");
194
[Link]();
📄 sessionStorage
What is it?
● Same as localStorage, but cleared when you close the browser tab or window.
Example:
[Link]("cart", "3 items");
[Link]([Link]("cart")); // 3 items
[Link]();
195
🔗 References:
● Web Storage API — MDN
● [Link] — MDN
🎯 Exercises:
1️⃣Set a cookie with your name and retrieve it.
2️⃣Save a user’s preferred language in localStorage.
3️⃣Store a temporary note in sessionStorage and clear it when the tab is closed.
4️⃣Write a function to clear all storage.
5️⃣Make a counter that increases every time the user reloads the page (use
localStorage).
Mini Project:
“Theme Switcher”
● JavaScript:
196
[Link] = () => {
[Link] = "black";
[Link] = "white";
[Link]("theme", "dark");
};
[Link] = () => {
[Link] = "white";
[Link] = "black";
[Link]("theme", "light");
};
[Link] = "black";
[Link] = "white";
📋 Quiz:
✅ Which storage lasts even after closing the browser?
● A) sessionStorage
● B) localStorage
● C) cookies
197
● D) Both B & C
● A) delete()
● B) removeItem()
● C) clear()
● D) erase()
● A) It’s slow
● B) It’s insecure
● C) It’s invisible
● D) It’s expensive
🌟 What it is:
Animations are visual changes that happen smoothly over time — like moving an object, fading
in/out, spinning, bouncing, etc.
JavaScript lets you create and control animations on a web page by changing element styles
over time.
198
🔷 Ways to Animate in JavaScript:
Method Description
Example:
<div id="box" style="width:50px;height:50px;background:red;position:absolute;"></div>
let pos = 0;
199
clearInterval(move);
} else {
pos++;
}, 10);
Example:
let box = [Link]("box");
let pos = 0;
function animate() {
pos++;
requestAnimationFrame(animate);
200
requestAnimationFrame(animate);
Example:
<div id="circle" style="width:50px;height:50px;background:blue;border-radius:50%;transition:all
2s;"></div>
[Link]("circle").onclick = () => {
[Link]("circle").[Link] = "translateX(200px)";
};
201
✅ Always provide fallback (e.g., user with motion disabilities may turn off
animations).
🔗 References:
● requestAnimationFrame — MDN
🎯 Exercises:
1️⃣Move a square to the right and stop at 200px.
2️⃣Make a circle grow from 20px to 100px size.
3️⃣Create a “fade out” effect where an element’s opacity becomes 0.
4️⃣Animate a ball bouncing up and down continuously.
5️⃣Combine CSS transitions & JS to slide a menu in and out.
Mini Project:
“Bouncing Ball”
let x = 0, y = 0;
let dx = 2, dy = 2;
202
function bounce() {
x += dx;
y += dy;
[Link] = x + "px";
[Link] = y + "px";
requestAnimationFrame(bounce);
bounce();
📋 Quiz:
✅ Which method is most efficient for smooth animations?
● A) setInterval()
● B) setTimeout()
● C) requestAnimationFrame()
● D) clearInterval()
● A) It’s faster.
203
● B) It syncs with the screen refresh rate.
● C) It stops automatically.
● D) Both A & B.
● A) stop()
● B) clearInterval()
● C) cancelAnimationFrame()
🌟 What it is:
Clean and efficient code is code that works correctly, is easy to understand, easy to
maintain, and runs fast enough for the user’s needs.
204
✨ Readability:
Code is read more often than it is written.
✅ Use meaningful variable and function names.
✅ Break code into small, clear functions.
✅ Indent properly and use consistent formatting.
Example:
❌ Bad:
✅ Good:
Example:
❌ Bad:
[Link]("item1").[Link] = "red";
[Link]("item2").[Link] = "red";
✅ Good:
function colorRed(id) {
[Link](id).[Link] = "red";
205
colorRed("item1");
colorRed("item2");
✨ Consistency:
✅ Use the same style and conventions throughout your code.
✅ If you’re on a team, follow the team’s coding guidelines.
Example:
const list = [Link]("li");
[Link](item => {
// Do something
});
206
✅ Minimize how often you read/write to the DOM — it can be slow.
✅ Use documentFragment for batch changes.
🔗 References:
● Clean Code principles
207
🎯 Exercises:
1️⃣Rewrite a messy function to make it more readable and DRY.
2️⃣Refactor a function with repetitive code into smaller helper functions.
3️⃣Add comments and meaningful names to an anonymous snippet.
4️⃣Find and remove redundant DOM queries in a sample script.
5️⃣Optimize a loop that does unnecessary calculations.
Mini Project:
“Todo List Refactor”
● Clean it up by:
○ Adding comments.
📋 Quiz:
✅ Why is clean code important?
● A) It runs faster
● D) Both A & B
208
● A) Don’t Repeat Yourself
● D) Both A & C
🌟 What it is:
Debugging means finding and fixing errors (bugs) in your code so it works as expected.
It’s a crucial skill because even expert developers make mistakes — but they know how to find
and solve them.
209
🪲 Error Type Example
Logic Error Code runs but produces the wrong result (hardest to find).
Example:
let num = 5;
210
🧰 Browser DevTools
✅ Every modern browser has built-in Developer Tools (usually opened with F12 or
Ctrl+Shift+I).
✅ Look at the Console tab for error messages.
✅ Use the Elements tab to inspect HTML & styles.
✅ Use the Sources tab to set breakpoints and step through code.
🔷 Breakpoints
Instead of filling your code with [Link](), you can pause execution at a specific
line in DevTools.
✅ Open DevTools → Sources tab → click the line number → refresh & watch code
stop there.
✅ Step line-by-line to see what happens.
🔷 Common Strategies:
✅ Read error messages carefully — they often tell you the line number & problem.
✅ Check your assumptions — is the variable really what you think it is?
✅ Simplify the problem — comment out sections to isolate the bug.
✅ Test with different inputs — see if the bug only happens in certain cases.
✅ Rubber duck debugging — explain the code out loud, even to a toy duck.
211
❌ Ignoring error messages — they are there to help!
❌ Assuming your code is correct without testing.
✅ Start small — check one thing at a time.
✅ Clean up your debugging code ([Link]) when you’re done.
✅ Learn to use breakpoints — they’re more powerful than just logs.
🔗 References:
● Debugging JavaScript — MDN
🎯 Exercises:
1️⃣Open DevTools and find a syntax error in a sample HTML+JS file.
2️⃣Add meaningful [Link]() statements to find where a loop goes wrong.
3️⃣Use a breakpoint to inspect a variable’s value when a button is clicked.
4️⃣Fix a TypeError by checking data types.
5️⃣Try explaining your code aloud and spot the bug yourself.
Mini Project:
“Buggy Calculator”
● Write a simple calculator script that has intentional bugs (like wrong operators, bad
variable names).
📋 Quiz:
✅ Which method is commonly used to print debug messages?
212
● A) print()
● B) [Link]()
● C) alert()
● D) debug()
● D) Delete a variable
✅ What’s the most important thing to do when you see an error message?
● A) Ignore it
● B) Read it carefully
🌟 What it is:
Performance optimization means making your code and web pages run faster, smoother, and
use less memory so that the user has a better experience.
It’s about improving the speed of your JavaScript and how efficiently your page behaves.
213
✅ Faster pages make users happy and keep them engaged.
✅ Reduces load on the browser and device (important for mobile users).
✅ Helps your site rank better in search engines (SEO).
✅ Saves bandwidth and power.
Example:
const fragment = [Link]();
[Link](div);
[Link](fragment);
214
✔ Instead of adding 1000 elements one by one, this adds them all at once.
✅ Changing layout-related properties (like width, height, top, left) forces the
browser to recalculate the page (reflow), which is expensive.
✅ Minimize how often you change these properties.
✨ Optimize Loops
✅ Don’t compute the same thing repeatedly inside a loop.
✅ Cache values outside the loop.
Example:
❌ Bad:
[Link]("li")[i].[Link] = "red";
✅ Good:
items[i].[Link] = "red";
215
✨ Lazy Load & Defer
✅ Don’t load all your scripts immediately if they’re not needed.
✅ Use <script defer> or load scripts after the page has loaded.
🔗 References:
● Performance Tips — MDN
216
🎯 Exercises:
1️⃣Rewrite a loop that queries the DOM repeatedly to cache the result.
2️⃣Build a page that inserts 500 elements efficiently.
3️⃣Compare two versions of code: one with many style changes, and one batched —
measure the difference.
4️⃣Add defer to a script and observe how it improves load time.
5️⃣Refactor a slow animation to use requestAnimationFrame.
Mini Project:
“Efficient Gallery”
● Create an image gallery where 100 thumbnails are added to the page.
● Make sure they load fast and don’t freeze the browser by batching DOM updates and
lazy loading images.
📋 Quiz:
✅ What slows down a page the most?
● A) Reading a variable
● C) Declaring a function
● D) Using [Link]
● A) Styling elements
● B) Animating elements
217
● C) Adding multiple DOM nodes without triggering reflows
● D) Removing elements
🌟 What it is:
Performance optimization means making your code and web pages run faster, smoother, and
use less memory so that the user has a better experience.
It’s about improving the speed of your JavaScript and how efficiently your page behaves.
218
🔷 Best Practices for Faster JavaScript:
✨ Minimize DOM Access
Example:
const fragment = [Link]();
[Link](div);
[Link](fragment);
✔ Instead of adding 1000 elements one by one, this adds them all at once.
✅ Changing layout-related properties (like width, height, top, left) forces the
browser to recalculate the page (reflow), which is expensive.
✅ Minimize how often you change these properties.
✨ Optimize Loops
219
✅ Don’t compute the same thing repeatedly inside a loop.
✅ Cache values outside the loop.
Example:
❌ Bad:
[Link]("li")[i].[Link] = "red";
✅ Good:
items[i].[Link] = "red";
220
❌ Loading giant libraries just for small functionality.
✅ Test your page’s performance regularly.
🔗 References:
● Performance Tips — MDN
🎯 Exercises:
1️⃣Rewrite a loop that queries the DOM repeatedly to cache the result.
2️⃣Build a page that inserts 500 elements efficiently.
3️⃣Compare two versions of code: one with many style changes, and one batched —
measure the difference.
4️⃣Add defer to a script and observe how it improves load time.
5️⃣Refactor a slow animation to use requestAnimationFrame.
221
Mini Project:
“Efficient Gallery”
● Create an image gallery where 100 thumbnails are added to the page.
● Make sure they load fast and don’t freeze the browser by batching DOM updates and
lazy loading images.
📋 Quiz:
✅ What slows down a page the most?
● A) Reading a variable
● C) Declaring a function
● D) Using [Link]
● A) Styling elements
● B) Animating elements
● D) Removing elements
222
● D) None of the above
🌟 What it is:
Progressive Enhancement and Graceful Degradation are two strategies for building websites
that work for everyone, no matter what browser, device, or connection they have.
● 📈 Progressive Enhancement: Start with the simplest, most basic functionality that works
everywhere, then add advanced features for browsers that can handle them.
● 📉 Graceful Degradation: Build with all the fancy features, but make sure it still works (in
some way) even if those features are not supported.
🔷 Progressive Enhancement:
🚀 How it works:
1️⃣Start with clean, semantic HTML → this ensures all content is visible and accessible.
2️⃣Add CSS → improves the design for browsers that support it.
3️⃣Add JavaScript → adds interactivity for capable browsers.
223
Example:
● Basic HTML form → works even if JS is off.
🌱 Real-world Example:
<!-- Basic HTML (works everywhere) -->
<button type="submit">Submit</button>
</form>
<script>
// Enhance with JS
[Link]();
if ([Link] < 3) {
} else {
});
</script>
224
🔷 Graceful Degradation:
🚀 How it works:
Example:
● Use CSS animations, but if the browser doesn’t support them → content still
visible & readable.
🌱 Real-world Example:
<div class="slider">
</div>
<script>
if (slider) {
</script>
225
🚨 Pitfalls & Best Practices:
❌ Don’t assume everyone has JS enabled — always provide a fallback.
❌ Don’t hide content behind JavaScript (e.g., rendering everything dynamically).
✅ Test your site with JS turned off & on slow connections.
✅ Make sure your HTML alone is meaningful & usable.
📋 Checklist:
✔ Semantic HTML as a solid base.
✔ External CSS & JS to enhance, not replace, core functionality.
✔ Test in different browsers, devices, and with JS disabled.
✔ Use noscript tags to show a helpful message when JS is off.
✔ Keep things simple first, then enhance.
🔗 References:
● Progressive Enhancement — MDN
🎯 Exercises:
226
1️⃣Build a page with a form that works without JS but validates with JS when enabled.
2️⃣Create a menu that is just a list in HTML but turns into a dropdown when JS is on.
3️⃣Test a page with JavaScript disabled (in browser settings) and fix any issues.
4️⃣Use noscript to show a message: “This site works better with JavaScript enabled.”
5️⃣Try your site on a slow mobile connection — see what loads & improve it.
Mini Project:
“Accessible Feedback Form”
📋 Quiz:
✅ What is the key idea of Progressive Enhancement?
● C) Removing accessibility
227
● D) Making pages slower on purpose
● B) Animations
● C) Sliders
🌟 What it is:
Accessibility (often abbreviated as a11y) means making your website usable by everyone,
including people with disabilities — such as vision, hearing, mobility, or cognitive impairments.
It ensures that all users can perceive, navigate, and interact with your web page, no matter their
abilities or technology (like screen readers).
228
🚫 Hiding or removing important content without alternatives.
🚫 Dynamically updating content without informing assistive technologies.
🚫 Custom UI components (like dropdowns, modals, sliders) that don’t follow accessibility
guidelines.
✅ JavaScript can also enhance accessibility when used correctly (like dynamic ARIA roles or
keyboard shortcuts).
🔷 Best Practices:
✨ Use Semantic HTML First
✅ Elements like <button>, <input>, <a> already have built-in keyboard & screen
reader support.
✅ Avoid replacing these with <div> or <span> unless absolutely necessary.
Example:
❌ Bad:
✅ Good:
Click me
</div>
229
✨ Use ARIA (Accessible Rich Internet Applications) Wisely
✅ Add ARIA roles & states when creating custom components.
✅ Example: adding aria-expanded, aria-hidden, role="dialog" to modals.
<p>Modal Content</p>
</div>
✅ Use aria-live regions so screen readers are informed when JS updates content.
<script>
</script>
✨ Test With:
✅ Keyboard only (Tab, Enter, Esc) — can you use the site fully?
✅ Screen readers (like NVDA, VoiceOver).
✅ High-contrast mode.
230
📄 Real-World Use Cases:
✅ A modal dialog that traps focus while open and returns focus when closed.
✅ A live chat box that announces new messages politely.
✅ A custom slider that works with arrow keys & announces its current value.
📋 Checklist:
✔ Semantic HTML wherever possible.
✔ Focusable and navigable interactive elements.
✔ Proper ARIA roles & states on custom components.
✔ Dynamic content is announced properly.
✔ Test with keyboard & screen readers.
🔗 References:
● Web Content Accessibility Guidelines (WCAG)
● MDN — Accessibility
🎯 Exercises:
1️⃣Make a custom “button” using <div> and make it fully keyboard accessible.
2️⃣Create a live region that updates a message dynamically.
3️⃣Add ARIA roles to a modal and trap focus inside it when open.
4️⃣Test your site without a mouse — can you complete all actions?
5️⃣Make a custom dropdown menu that works with arrow keys & announces its state.
Mini Project:
231
“Accessible Modal Dialog”
📋 Quiz:
✅ Why should you prefer <button> over <div> for clickable elements?
● D) No reason
232
● D) A button with proper ARIA roles.
🌟 What it is:
An ES Module (or JavaScript Module) is a way to organize your JavaScript code by splitting it
into reusable, self-contained files.
Bundling is the process of combining many JavaScript (and other) files into one (or a few) files
for better performance in browsers.
● Import: Bring something from another file into the current file.
✅ Named Export:
233
// file: [Link]
return a + b;
✅ Default Export:
// file: [Link]
📄 Import
[Link](add(2, 3)); // 5
[Link](PI); // 3.1415
234
✅ Renaming imports:
[Link](sum(5, 5)); // 10
🔷 What is Bundling?
When you build a real-world project, you might have dozens or hundreds of JS, CSS, and image
files.
Downloading so many files can slow down your site.
Bundlers (like Webpack, Parcel, Rollup) combine everything into one or a few optimized files.
<script src="[Link]"></script>
<script src="[Link]"></script>
235
<script src="[Link]"></script>
📋 Checklist:
✔ Use ES Modules for all new projects.
✔ Keep modules small & focused (Single Responsibility Principle).
✔ Name your files clearly ([Link], [Link]).
✔ Use a bundler when deploying a site for better performance.
✔ Test your bundle to ensure everything works as expected.
🔗 References:
● MDN — Import & Export
● MDN — ES Modules
● Webpack
● Parcel
🎯 Exercises:
236
1️⃣Create two modules ([Link] and [Link]) and import a function.
2️⃣Write a [Link] module exporting add, subtract, multiply, and use them in [Link].
3️⃣Refactor an existing big JS file into smaller modules.
4️⃣Use a default export in one file & a named export in another — import both in a main file.
5️⃣Explore an online bundler (like Parcel Playground) to bundle a small project.
Mini Project:
“Modular To-Do List”
📋 Quiz:
✅ What is the main benefit of using ES Modules?
● A) Faster typing
237
export default something;
● A) To confuse developers
🌟 What it is:
Exercises are small, focused challenges designed to help you practice each concept you’ve
learned in JavaScript and Web Development.
They test your understanding, improve your problem-solving skills, and build confidence step
by step.
238
✨ Don’t worry if you fail — look at the solution afterward and understand it.
✨ Try to modify or improve the solution.
Control Flow
239
1️⃣1️⃣Write a function greet that takes a name and returns “Hello, name!”.
1️⃣2️⃣Write an arrow function to square a number.
1️⃣
2️⃣
1️⃣3️⃣Write a closure that keeps track of a counter.
1️⃣
3️⃣
Strings
Objects
🟢 DOM Manipulation
240
2️⃣7️⃣Save a value to localStorage and then read it back.
2️⃣8️⃣Make a simple clock using setInterval that updates every second.
2️⃣
8️⃣
🟢 Advanced Topics
📋 Tips:
✔ Start with easy exercises & work your way up.
✔ Don’t skip the hard ones — that’s where the learning happens.
✔ Time yourself & try to improve each time.
✔ Discuss your solutions with others or explain them aloud.
🔗 References:
● MDN — JavaScript Guide
● [Link]
🎯 Challenge Yourself:
💡 After finishing all exercises above, try to combine 2–3 concepts in a single small script.
💡 Example: Write a function that reads from an <input>, validates the text, and saves it in
localStorage.
Bonus Exercise:
241
Build a simple counter on a page:
📋 Quiz:
✅ Why is it important to practice coding exercises?
✅ What should you do if you can’t solve an exercise right away?
✅ How can exercises prepare you for real-world development?
🌟 What it is:
Mini projects are small, focused, real-world applications you build to practice combining the
skills you’ve learned.
They help you move beyond simple exercises and start thinking like a developer.
242
🔷 How to Approach Mini Projects:
✨ Read the description carefully and visualize what you want it to look & behave
like.
✨ Break it into smaller tasks.
✨ Start with basic functionality, then improve it step-by-step.
✨ Keep your code organized — use comments, clear names, and modules if
needed.
✨ Test thoroughly and refine.
Features:
Concepts Practiced:
● DOM manipulation.
● String formatting.
Features:
243
Concepts Practiced:
● Basic arithmetic.
Features:
Concepts Practiced:
● Event listeners.
● DOM updates.
Features:
Concepts Practiced:
244
● Events & event delegation.
● localStorage.
Features:
Concepts Practiced:
● String manipulation.
245
✔ Test all scenarios & edge cases.
✔ Bonus: challenge yourself with enhancements.
🔗 References:
● MDN — DOM Manipulation
● MDN — setInterval
● MDN — localStorage
246
🌟 What it is:
These are capstone projects and a final assessment challenge — your chance to bring
everything you’ve learned into real, functional, professional-level web applications.
These projects simulate real-world scenarios and showcase your skills in a portfolio-worthy
way.
By the time you complete these, you won’t just know JavaScript — you’ll have proven it.
Features:
247
Skills Practiced:
● Event delegation.
● Array manipulation.
● localStorage.
● CSS styling.
🎯 Project 2 — Calculator
Goal: Build a simple calculator that performs basic arithmetic operations.
Features:
Skills Practiced:
● Event handling.
Features:
Skills Practiced:
248
● Forms & inputs.
Features:
Skills Practiced:
● Event handling.
Features:
Skills Practiced:
249
● Event handling.
● DOM manipulation.
● State tracking.
🎯 Challenge:
You are tasked with creating a single, interactive webpage that combines everything you’ve
learned so far — a professional-level, polished, and fully functional mini-application.
🚀 Description:
✨ You’re creating an interactive landing page for a fictional product/service that
demonstrates:
● DOM manipulation
Example Scenario:
You’re building a page for a fictional café called “JavaScript Beans”.
Here are suggested requirements:
250
📝 Features:
✅ Header with navigation menu that highlights the current section.
✅ Hero section with a button that scrolls to another part of the page.
✅ Menu section where items load dynamically from a JavaScript array.
✅ Feedback form with live validation (name, email, message).
✅ A counter showing how many people visited today (stored in localStorage).
✅ Animations when sections appear on scroll.
✅ Accessible — all interactive elements are keyboard-friendly and use semantic
HTML.
✅ Responsive layout (optional, if you’re comfortable with CSS).
🧩 Skills Practiced:
● Planning & structuring code.
📋 Final Tips:
✅ Treat these projects as if you’re building them for a real client.
✅ Spend time on both functionality & usability.
✅ Make sure your code is clear, commented, and well-organized.
✅ Test your apps on different browsers and screen sizes.
✅ Challenge yourself to add enhancements — but only after the core functionality
works.
251
🔗 Useful References for Final Projects:
● MDN Web Docs
● [Link]
252