[Go to site: main page, start]

0% found this document useful (0 votes)
3 views138 pages

Java Script

The document provides a comprehensive overview of JavaScript, covering its dynamic capabilities, variable types, data types, operators, and control structures. It includes practical examples of DOM manipulation, user input handling, type conversion, and the use of built-in objects like Math. Additionally, it emphasizes best practices for writing clean and efficient JavaScript code.

Uploaded by

tylerkatsha14
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)
3 views138 pages

Java Script

The document provides a comprehensive overview of JavaScript, covering its dynamic capabilities, variable types, data types, operators, and control structures. It includes practical examples of DOM manipulation, user input handling, type conversion, and the use of built-in objects like Math. Additionally, it emphasizes best practices for writing clean and efficient JavaScript code.

Uploaded by

tylerkatsha14
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

JavaScript

Sunday, July 6, 2025 1:48 AM

• JavaScript makes webpages dynamic and interactive


• Add using the <script> tag or external .js file in HTML.
• [Link]() outputs message for testing.

Variables:

• var(older), let(block-scoped), const(constant)

Data types:

• Primitive: string, number, boolean, null, undefined


• Complex: array, object, function

Operators:

• Arithmetic: + , - , * , / , %
• Comparison: == , ===, !=, <, >
• Logical: &&, ||, !

Comments:

• Single-line: //
• Multi-line: /**/

Conditions:

• if, else if, else control flow


• switch checks multiple values

Loops:

• For (fixed iteration)


• While (runs whole condition true)
• do..while (runs at least once)
• Control with break, continue

• Functions:
○ Declared: function greet() {}
○ Return values with return
○ Parameters pass data to functions
○ Arrow functions: const sum = (a,b) => a + b

• Scope:

○ Local: (inside functions)


○ Global: (outside functions)

Arrays:

JavaScript Page 1
Arrays:

• Store lists: let items = [1,2,3]


• Access with index items[0]
• Methods: push(), pop(), shift(), unshift(), length

Objects:

• Store key-value pairs: let user = {name: "Alex", age: 30}


• Access with [Link] or user['age']

DOM Manipulation:

• Select elements: getElementById(), querySelector()


• Change content: innerHTML, textContent
• Modify style: [Link] = "red"

• Additional:

○ JSON: [Link]() to convert to string


○ [Link]() to convert back
○ Error handling: try…catch
○ Template literals: `Hello ${name}`
○ ES6 features: destructuring, spread/rest operators

• Best Practices:

○ Use let and const (avoid var)


○ Comment your clear clearly
○ Write clean, reuseable functions
○ Test with browser DevTools console

JavaScript Page 2
JavaScript for beginners
Monday, July 21, 2025 8:33 PM

JS Page
-------------------------------------------------------------------
/*[Link](`Hello`);
[Link](`I like pizza`);
[Link](`This is an Alert`);
[Link](`I like Pizza`);
*/
[Link]("MyH1").textContent = "Hello";
[Link]("MyP").textContent = "I like Pizza";
//This is an comment
/*
This
is
an
comment
*/
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<h1 id="MyH1"></h1>
<p id="MyP"></p>
<script src="[Link]"></script>
-------------------------------------------------------------------

JavaScript Page 3
Variables
Monday, July 21, 2025 8:34 PM

Variable = A container that stores a value. Behaves as if it were the


value it contains.

1. Declaration let x;
2. Assignment x = 100;

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
/*let age = 25;
let price = 10.99;
let gpa = 2.1;
let firstname = "Tyler";
let favFood = "Pizza";
let email = "tyler134@[Link]";
[Link](typeof age);
[Link](typeof firstname);
[Link](firstname);
[Link](`Your first name is ${firstname}`);
[Link](`You like ${favFood}`);
[Link](`Your email is ${email}`);
[Link](`You are ${age} years old`);
[Link](`The price is ${price}`);
[Link](`Your gpa is ${gpa}`);
let >let forsale = false;
let enrolled = true;
//[Link](typeof online);
[Link](`Bro is online: ${online}`);
[Link](`Is this car for sale: ${forsale}`);
[Link](`Enrolled: ${enrolled}`);
*/
let fullName = "Tyler Katsha";
let isStudent = true;
let age = 18;
//[Link]("p1").textContent = fullName;
//[Link]("p2").textContent = isStudent;
//[Link]("p3").textContent = age;
[Link]("p1").textContent = `Your name is
${fullName}`;
[Link]("p2").textContent = `Enrolled: ${isStudent}`;
[Link]("p3").textContent = `You are ${age} years
old`;
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script src="[Link]"></script>
-------------------------------------------------------------------

JavaScript Page 4
Arithmetic operators
Monday, July 21, 2025 9:14 PM

Arithmetic operators = operands (values, variables, etc.), operatoes


( + , - , * , / )
ex. 11 = x + 5;

Operator precedence

1 Brackets()
2 exponents
3 multiplication & division & modulus
4 addition & subtraction

Note: 's' is short for students

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let s = 30;

//s = s - 1;
//s = s + 2;
//s = s * 3;
//s = s / 4;
//s = s ** 5;
//let extrastudent = s % 6;

//using augmented assignment operators


//s += 1;
//s -= 2;
//s *= 3;
//s /= 4;
//s **= 5;
//s %= 6;
//s++;
//s--;
[Link](s);

let result = 1 + 2 * 3 + 4 ** 2;
result = 12 % 5 + 8 / 2;
result = 6 / 2 ** (2 + 5);
[Link](result);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">

JavaScript Page 5
1.0">
<title>Document</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 6
Accept User input
Monday, July 21, 2025 9:14 PM

How to accept user input

1. Easy way = window prompt

2. Professional way = HTML textbox

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//let username = [Link]("What's your username?");
//[Link](username);
let username;
[Link]("mySubmit"). > username = [Link]("myText").value;
[Link]("myH1").textContent = `Hello ${username}`;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>JS ACCEPT USER INPUT</title>
</head>
<body>
<h1 id="myH1">Welcome</h1>
<label>username:</label>
<input id="myText"><br><br>
<button id="mySubmit">submit</button>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 7
Type Conversion
Monday, July 21, 2025 9:16 PM

Change the datatype of a value to another (strings, numbers, booleans)

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// let age = [Link]("What is your age?")
// age = Number(age);
// age+=1
// [Link](age, typeof age);
let x;
let y;
let z;
x = Number(x);
y = String(y);
z = Boolean(z);
[Link](x, typeof x);
[Link](y, typeof y);
[Link](z, typeof z);
-------------------------------------------------------------------
Output
-------------------------------------------------------------------

-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>JS TYPE CONVERSION</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 8
Constants
Monday, July 21, 2025 9:16 PM

A variable that can't be changed

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const PI = 3.14159;
let radius;
let circumference;
//radius = [Link]("Enter the radius of a circle");
[Link]("mySubmit"). > radius = [Link]("myText").value;
radius = Number(radius);
circumference = 2 * PI * radius;
[Link]("myH3").textContent = circumference +
"cm";
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>JS CONSTANT</title>
</head>
<body>

<h1 id="myH1">Enter the radius of a circle:</h1>


<label>radius:</label>
<input type="text" id="myText"><br><br>
<button id="mySubmit">Submit</button>
<h3 id="myH3"></h3>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 9
Counter Program
Monday, July 21, 2025 9:16 PM

JS Page
-------------------------------------------------------------------
const decreaseBtn = [Link]("decreaseBtn");
const resetBtn = [Link]("resetBtn");
const increaseBtn = [Link]("increaseBtn");
const countLabel = [Link]("countLabel");
let count = 0;
[Link] = function(){
count++;
[Link] = count;
}
[Link] = function(){
count--;
[Link] = count;
}
[Link] = function(){
count = 0;
[Link] = count;
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
background-color: #2926c9;
}
#countLabel{
display: block;
text-align: center;
font-size: 10em;
font-family: Arial, Helvetica, sans-serif;
}
#btnContainer{
text-align: center;
}
.buttons{
padding: 10px 20px;
margin: 10px;
font-size: 1.5em;
color: white;
background-color: rgb(29, 185, 55);
cursor: pointer;
border-radius: 8px;
border-style: none;
transition: scale 0.15s;
}
.buttons:hover{
scale: 1.1;
}
.buttons:active{
scale: 0.8;

JavaScript Page 10
scale: 0.8;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<link rel="stylesheet" href="[Link]">
<title>JS COUNTER PROGRAM</title>
</head>
<body>
<label id="countLabel">0</label><br>
<div id="btnContainer">
<button id="decreaseBtn" class="buttons">Decrease</button>
<button id="resetBtn" class="buttons">Reset</button>
<button id="increaseBtn" class="buttons">Increase</button>
</div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 11
Math Object
Monday, July 21, 2025 9:18 PM

Built-in object that provides a collection of properties and methods

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// [Link]
// [Link]([Link])
// [Link](Math.E)
// let x = 3.12;
let x = 3;
let y = 2;
// let z;
let z = 1;
//z = [Link](x); rounds the number
//z = [Link](x); gets the floor of the number
//z = [Link](x); gets the floor of the number
//z = [Link](x); gets rid of the decimal portion
//z = [Link](x,y); power function
// z = [Link](x); square root function
// z = [Link](y); log function
// z = [Link](x); sin function
// z = [Link](x); cos function
// z = [Link](x); tan function
// z = [Link](x); absloute value
// z = [Link](x); gets the sign of the number
// let max = [Link](x,y,z); finds the biggest number
let min = [Link](x,y,z); finds the smallest number
// [Link](z);
// [Link](max);
[Link](min);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>JS MATH OBJECT</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 12
Random number generator
Monday, July 21, 2025 9:18 PM

JS Page
-------------------------------------------------------------------
// const min = 50;
// const max = 100;
// let randomNum = [Link]([Link]()*(max-min)) + min;

// [Link](randomNum);
const myBtn = [Link]("myBtn");
const myLabel1 = [Link]("myLabel1");
const myLabel2 = [Link]("myLabel2");
const myLabel3 = [Link]("myLabel3");
const min = 1;
const max = 6;
let randomNum1;
let randomNum2;
let randomNum3;

[Link] = function(){
randomNum1 = [Link]([Link]() * max) + min;
randomNum2 = [Link]([Link]() * max) + min;
randomNum3 = [Link]([Link]() * max) + min;
[Link] = randomNum1;
[Link] = randomNum2;
[Link] = randomNum3;
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-align: center;
}
#myBtn{
font-size: 3em;
padding: 5px 25px;
border-radius: 8px;
}
.myLabel{
font-size: 3em;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">

JavaScript Page 13
1.0">
<title>Random Number Generator PROGRAM</title>
</head>
<body>
<button id="myBtn">Roll</button><br>
<label id="myLabel1" class="myLabel"></label><br>
<label id="myLabel2" class="myLabel"></label><br>
<label id="myLabel3" class="myLabel"></label><br>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 14
If statements
Monday, July 21, 2025 9:18 PM

If a condition is true, execute some code.


If not, do something else

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// let age = 13;
// if(age >= 18){
// [Link]("You are old enough to enter this site");
// }
// else{
// [Link]("You must 18+ to enter this site");
// }
// let time = 9;
// if(time < 12){
// [Link]("Good morning");
// }
// else{
// [Link]("Good afternoon");
// }
// let isStudent = true;
// if(isStudent){
// [Link]("You are a student");
// }
// else{
// [Link]("You are not a student");
// }
// let age = 75;
// let hasLicense = true;
// if(age >= 16){
// [Link]("You are old enough to drive");
// if(hasLicense){
// [Link]("You have your license");
// }
// else{
// [Link]("You dont have your license yet")
// }
// }
// else{
// [Link]("You must be 16+ to have a license");
// }
const myText = [Link]("myText");
const mySubmit = [Link]("mySubmit");
const resultElement = [Link]("resultElement");
let age;
[Link] = function(){
age = [Link];
age = Number(age);
if(age >= 100){
[Link] = `You are TOO OLD to enter this

JavaScript Page 15
[Link] = `You are TOO OLD to enter this
site`;
}
else if(age == 0){
[Link] = `You can't enter. You were just born`;
}
else if(age >= 18){
[Link] = `You are old enough to enter this
site`;
}
else if(age < 0){
[Link] = `Your age can't be below 0`;
}
else{
[Link] = `You must 18+ to enter this site`;
}
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>If statements</title>
</head>
<body>
<label>Enter your age:</label><br>
<input type="text" id="myText"><br>
<button type="submit" id="mySubmit">Submit</button>
<p id="resultElement"></p>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 16
Checked Property
Monday, July 21, 2025 9:18 PM

Property that determines the checked state of an HTML checkbox or


radio button element

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const myCheckBot = [Link]("myCheckBox");
const visaBtn = [Link]("visaBtn");
const masterCardBtn = [Link]("masterCardBtn");
const payPalBtn = [Link]("payPalBtn");
const mySubmit = [Link]("mySubmit");
const subResult = [Link]("subResult");
const paymentResult = [Link]("paymentResult");
[Link] = function(){
if([Link]){
[Link] = `You are subscribed!`;
}
else{
[Link] = `You are not subscribed!`;
}
if([Link]){
[Link] = `You are paying with Visa`;
}
else if([Link]){
[Link] = `You are paying with MasterCard`;
}
else if([Link]){
[Link] = `You are paying with PayPal`;
}
else{
[Link] = `You must select a payment type`;
}
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 2em;
}
#mySubmit{
font-size: 1em;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

JavaScript Page 17
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<link rel="stylesheet" href="[Link]">
<title>Checked Property</title>
</head>
<body>
<input type="checkbox" id="myCheckBox">
<label for="myCheckBox" >Subscribe</label><br><br>
<input type="radio" id="visaBtn" name="card">
<label for="visaBtn">Visa</label><br>
<input type="radio" id="masterCardBtn" name="card">
<label for="masterCardBtn">Master Card</label><br>
<input type="radio" id="payPalBtn" name="card">
<label for="payPalBtn">PayPal</label><br><br>
<button type="submit" id="mySubmit">submit</button>
<p id="subResult"></p>
<p id="paymentResult"></p>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 18
Ternary Operators
Monday, July 21, 2025 9:19 PM

A shortcut to if{} and else{} statements helps to assign a variable


based on a condition

Syntax:

condition ? codeIfTrue : codeIfFalse;

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// let age = 18;
// let message = age >= 18 ? "You're an adult" : "You're a minor";
// [Link](message);
// let time = 14;
// let greeting = time < 12 ? "Good morning" : "Good Afternoon";
// [Link](greeting);
// let isStudent = true;
// let message = isStudent ? "You are a student" : "You are not a
student";
// [Link](message);
let purchaseAmount = 125;
let discount = purchaseAmount >= 100 ? 10 : 0;
[Link](`Your total is $${purchaseAmount - purchaseAmount *
(discount/100)}`);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Ternary Operator</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 19
Switches
Monday, July 21, 2025 9:19 PM

Can be an efficient replacement to many else if statements

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// let day = 1;
// switch(day){
// case 1:
// [Link]("it's Monday");
// break;
// case 2:
// [Link]("it's Tuesday");
// break;
// case 3:
// [Link]("it's Wednesday");
// break;
// case 4:
// [Link]("it's Thursday");
// break;
// case 5:
// [Link]("it's Friday");
// break;
// case 6:
// [Link]("it's Saturday");
// break;
// case 7:
// [Link]("it's Sunday");
// break;
// default:
// [Link](`${day} is not a day`)
// }
let testScore = 92;
let letterGrade;
switch(true){
case testScore >= 90:
letterGrade = "A";
break;
case testScore >- 80:
letterGrade = "B";
break;
case testScore >- 70:
letterGrade = "C";
break;
case testScore >- 60:
letterGrade = "D";
break;
default:
letterGrade = "F";
}
[Link](letterGrade);

JavaScript Page 20
[Link](letterGrade);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Switch</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 21
String Methods
Monday, July 21, 2025 9:19 PM

Allow you to manipulate and work with text (strings)

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let userName = "TylerKatsha";
[Link]([Link](0));
[Link]([Link]("a"));
[Link]([Link]("a"));
[Link]([Link]);
userName = [Link]();
userName = [Link]();
userName = [Link]();
userName = [Link](2);
// let result = [Link]("T");
// if(result){
// [Link]("Your username can't begin with ' '");
// }
// else{
// [Link](userName);
// }
// let result = [Link]("");
// if(result){
// [Link]("Your username can't end with ' '");
// }
// else{
// [Link](userName);
// }
let result = [Link](" ");
if(result){
[Link]("Your username can't include ' '");
}
else{
[Link](userName);
}

let phoneNumber = "123-456-7890";


phoneNumber = [Link]("-","");
//phoneNumber = [Link](15,"0");
phoneNumber = [Link](15,"0");
[Link](phoneNumber);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">

JavaScript Page 22
1.0">
<title>String Methods</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 23
String Slicing
Monday, July 21, 2025 9:19 PM

Creating a substring from a portion of another string

[Link](start,end)

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const fullName = "Tyler Katsha";
// let firstName = [Link](0,5);
// let lastName = [Link](6);
// [Link](firstName);
// [Link](lastName);
// let firstChar = [Link](0,1);
// let lastChar = [Link](-1);
// [Link](firstChar);
// [Link](lastChar);
// let firstName = [Link](0,[Link](" "));
// let lastName = [Link]([Link](" ") + 1);
// [Link](firstName);
// [Link](lastName);
const email = "tyler@[Link]";
let userName = [Link](0,[Link]("@"));
let extension = [Link]([Link]("@") + 1);
[Link](userName);
[Link](extension);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>String Slicing</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 24
Method of Chaining
Monday, July 21, 2025 9:19 PM

Calling one method after another in one continuous line of code

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let username = [Link]("Enter your username: ");
// ----- No Method Chaining -----
// username = [Link]();
// let letter = [Link](0);
// letter = [Link]();
// let extraChars = [Link](1);
// extraChars = [Link]();
// username = letter + extraChars;
// [Link](username);
// ----- Method Chaining -----
username = [Link]().charAt(0).toUpperCase() +
[Link]().slice(1).toLowerCase();
[Link](username);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Method of Chaining</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 25
Logical Operators
Monday, July 21, 2025 9:19 PM

Used to combine or manipulate boolean valus (true or false)

Syntax of LO:
-----------
AND = &&
OR = ||
NOT = !
-----------

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const temp = 29;
// if(temp > 0 && temp <= 30){
// [Link]("The weather is GOOD");
// }
// else{
// [Link]("The weather is BAD");
// }
if(temp <= 0 || temp > 30){
[Link]("The weather is BAD");
}
else{
[Link]("The weather is GOOD");
}
const isSunny = true;
// if(isSunny){
// [Link]("It is SUNNY");
// }
// else{
// [Link]("It is CLOUDY");
// }
if(!isSunny){
[Link]("It is CLOUDY");
}
else{
[Link]("It is SUNNY");
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Logical Operator</title>
</head>
<body>

JavaScript Page 26
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 27
Strict equality
Monday, July 21, 2025 9:19 PM

`=`--> assignment operator


`==` --> comparison operator (compare if values are equal)
`===` --> strict equality operator (compare if values & datatype are
equal)
`!=` --> inequality operator
`!==` --> strict inequality operator

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const PI = 3.14;
// if (PI == "3.14"){
// [Link]("That is Pi");
// }
// else{
// [Link]("That is NOT Pi");
// }
//Output: That is Pi
// if (PI === "3.14"){
// [Link]("That is Pi");
// }
// else{
// [Link]("That is NOT Pi");
// }
//Output: That is NOT Pi
// if (PI != "3.14"){
// [Link]("That is NOT Pi");
// }
// else{
// [Link]("That is Pi");
// }
//Output: That is Pi
if (PI !== "3.14"){
[Link]("That is NOT Pi");
}
else{
[Link]("That is Pi");
}
//Output: That is NOT Pi
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Strict equality</title>
</head>

JavaScript Page 28
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 29
While loops
Monday, July 21, 2025 9:19 PM

Repeat some code WHILE some condition is true.

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//let username = "";
//while loop
// while(username === "" || username === null){
// username = [Link](`Enter your name`);
// }
// let username;
//do-while loop
// do{
// username = [Link](`Enter your name`);
// }while(username === "" || username === null);
// [Link](`Hello ${username}`);
//while loop
// let loggedIn = false;
let username;
let password;
// while(!loggedIn){
// username = [Link](`Enter your username`);
// password = [Link](`Enter your password`);
// if(username === "myUsername" && password === "myPassword"){
// loggedIn = true;
// [Link]("You are logged in");
// }
// else{
// [Link]("Invalid credentials! Please try again")
// }
// }

//do-while loop
let loggedIn = true;
do{
username = [Link](`Enter your username`);
password = [Link](`Enter your password`);
if(username === "myUsername" && password === "myPassword"){
loggedIn = true;
[Link]("You are logged in");
}
else{
[Link]("Invalid credentials! Please try again")
}
}while(!loggedIn);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">

JavaScript Page 30
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>While Loops</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 31
For loops
Monday, July 21, 2025 9:19 PM

Repeat some code a LIMITED amount of times

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// for(let i = 10; i > 0;i--){
// // [Link]("Hello");
// [Link](i);
// }
// [Link]("Happy NEW YEAR!")
// for(let i = 1;i <= 20;i++){
// if(i == 13){
// continue;
// }
// [Link](i);
// }
for(let i = 1;i <= 20;i++){
if(i == 13){
break;
}

[Link](i);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>For Loops</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 32
Number guessing game
Monday, July 21, 2025 9:19 PM

JS Page
-------------------------------------------------------------------
const minNum = 1;
const maxNum = 100;
const answer = [Link]([Link]() * (maxNum - minNum + 1)) +
minNum;
let attempts = 0;
let guess;
let running = true;
//[Link](answer);
while(running){
guess = [Link](`Guess a number between ${minNum} -
${maxNum}`);
//[Link](typeof guess, guess);
guess = Number(guess);
if(isNaN(guess)){
[Link]("Please enter a valid number");
}
else if(guess < minNum || guess > maxNum){
[Link]("Please enter a valid number");
}
else{
attempts++;
if(guess < answer){
[Link]("TOO LOW! TRY AGAIN");
}
else if(guess > answer){
[Link]("TOO HIGH! TRY AGAIN");
}
else{
[Link](`Correct! The answer was ${answer}. It took you
${attempts} attempts`)
running = false;
}
}
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>NGG</title>
</head>
<body>
<script src="[Link]"></script>
</body>

JavaScript Page 33
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 34
Functions
Monday, July 21, 2025 9:19 PM

A section of reusable code. Declare code once, use it whenever you


want. Call the function to execute that code

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// function happyBirthday(username,age){
// [Link](`Happy birthday to you!`);
// [Link](`Happy birthday to you!`);
// [Link](`Happy birthday dear ${username}!`);
// [Link](`Happy birthday to you!`);
// [Link](`you are ${age} years old`);
// }
// happyBirthday("Tyler",18);
// happyBirthday("Spongebob",30);
// happyBirthday("Patrick",37);

function add(x,y){
return x + y;
}
function subtract(x,y){
return x - y;
}
function multiply(x,y){
return x * y;
}
function divide(x,y){
if(y !== 0){
return x / y;
}
return 0;
}
[Link](add(2,3));
[Link](subtract(2,3));
[Link](multiply(2,3));
[Link](divide(2,3));
function isEven(number){
return number % 2 == 0 ? true : false;
}
[Link](`Even number: ${isEven(12)}`);
[Link](`Even number: ${isEven(13)}`);
function isValidEmail(email){
return [Link]("@") ? true : false;
}
[Link](`Valid email: ${isValidEmail("tyler01@.gmail")}`);
[Link](`Valid email: ${isValidEmail("[Link]")}`);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>

JavaScript Page 35
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Functions</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 36
Variable Scope
Monday, July 21, 2025 9:19 PM

Where a variable can be accessed.

Two types of Variable scopes


Local and class scope

Local scope:
Variable defined inside a function/method, accessible only there

Class scope:
Variable defined at the class level (often shared by all objects)

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//Global scope
let x = 3;
function1();
function2();
[Link](x);
function function1(){
//local scope
let x = 1;
[Link](x);
}
function function2(){
//local scope
let x = 2;
[Link](x);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Variable Scope</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 37
Temperature conversion program
Monday, July 21, 2025 9:19 PM

JS Page
-------------------------------------------------------------------
const textBox = [Link]("textBox");
const toFahrenheit = [Link]("toFahrenheit");
const toCelsius = [Link]("toCelsius");
const result = [Link]("result");
let temp;
function convert(){

if([Link]){
temp = Number([Link]);
temp = temp * (9 / 5) + 32;
[Link] = [Link](1) + "°F"
}
else if([Link]){
temp = Number([Link]);
temp = (temp - 32) * (5/9);
[Link] = [Link](1) + "°C"
}
else{
[Link] = "Select a unit";
}
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
font-family: Verdana, Geneva, Tahoma, sans-serif;
background-color: rgb(216, 216, 216);
}
h1{
color: blue;
}
form{
background-color: white;
text-align: center;
max-width: 350px;
margin: auto;
padding: 25px;
border-radius: 10px;
box-shadow: 5px 5px 15px black;
}
#textBox{
width: 50%;
text-align: center;
font-size: 2em;
border: 2px solid rgba(15, 224, 155, 0.8);
border-radius: 8px;
box-shadow: 3px 3px 8px rgba(15, 224, 155, 0.8);
margin-bottom: 15px;

JavaScript Page 38
margin-bottom: 15px;
cursor: pointer;
}
label{
font-size: 1.5em;
font-weight: bold;
}
button{
margin-top: 15px;
background-color: white;
border: 1px solid rgba(15, 224, 155, 0.8);
font-size: 1.5em;
box-shadow: 3px 3px 8px rgba(15, 224, 155, 0.8);
border-radius: 5px;
cursor: pointer;
padding: 10px 15px;
transition: background-color 0.15s,
scale 0.15s,
box-shadow 0.15s;
}
button:hover{
scale: 1.1;
box-shadow: 3px 3px 8px white;
background-color: rgba(15, 224, 155, 0.8);
}
button:active{
scale: 0.9;
}
#result{
font-size: 1.75em;
font-weight: bold;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Temp Conversion Program</title>
</head>
<body>
<form>
<h1>Temperature Conversion</h1>
<input type="number" id="textBox" value="0"><br>
<input type="radio" id="toFahrenheit" name="unit">
<label for="toFahrenheit">Celsius ➡ Fahrenheit</label><br>
<input type="radio" id="toCelsius" name="unit">
<label for="toCelsius">Fahrenheit ➡ Celsius</label><br>
<button type="button" > <p id="result">Select a unit</p>
</form>

JavaScript Page 39
</form>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 40
Arrays
Monday, July 21, 2025 9:19 PM

A variable like structure that can hold more than 1 value

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let fruits = ["apple","orange","banana"];
//fruits[3] = "coconut";
// [Link]("coconut");
//[Link]("mango");
//[Link]();
// let numOfFruits = [Link];
// let index = [Link]("apple");
// [Link]("Apple found at index: " + index);
// [Link](fruits[0]);
// [Link](fruits[1]);
// [Link](fruits[2]);
// [Link](fruits[3]);
// [Link]();
// [Link](fruits[3]);
for(let i = 0 ;i< [Link]; i++){
[Link](fruits[i]);
}
[Link]().reverse();
for(let j = [Link] - 1 ;j>=0 ; j--){
[Link](fruits[j]);
}
[Link]();
for(let fruit of fruits){
[Link](fruit);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Arrays</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 41
Spread Operators
Monday, July 21, 2025 9:19 PM

… allows an iterable such as an array of string to be expanded into


separate elements (unpacks the elements)

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let numbers = [1,2,3,4,5];
let maximum = [Link](...numbers);
let minimum = [Link](...numbers);
[Link](maximum);
[Link](minimum);
let username = "Bro code";
let letters = [...username].join("-");
[Link](letters);
let fruits = ["apple","orange","banana"];
let vegetables = ["carrots","celery","potatoes"];
let foods = [...fruits,...vegetables,"eggs","milk"];
let newFruits = [...fruits]; //creates a shallow copy of fruits
[Link](fruits);
[Link](newFruits);
[Link](foods);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Spread Operator</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 42
Rest parameters
Monday, July 21, 2025 9:19 PM

(…rest) allow a function work with a variable number of arguments by


bundling them into an array.

Spread = expands an array into seperate elements


Rest = bundles separate elements into an array

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
function openFridge(...foods){
[Link](...foods);
}
function getFood(...foods){
return foods;
}
const food1 = "pizza";
const food2 = "hamburger";
const food3 = "sushi";
const food4 = "hotdog";
const food5 = "ramen";
//openFridge(food1,food2,food3,food4,food5);
const foods = getFood(food1,food2,food3,food4,food5);
[Link](foods);
function sum(...numbers){
let result = 0;
for(let number of numbers){
result += number;
}
return result;
}
const total = sum(1,2,3,4,5);
[Link](`Your total is $${total}`)
function getAverage(...numbers){
let result = 0;
for(let number of numbers){
result += number;
}
return result/[Link];
}
const totalA = getAverage(75,100,90,85,50);
[Link](`The average is ${totalA}`);
function combineStrings(...strings){
return [Link](" ");
}
const fullName =
combineStrings("Mr","Spongbob","Squarepants","III");
[Link](fullName);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------

JavaScript Page 43
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Rest parameters</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 44
Dice Roller Program
Monday, July 21, 2025 9:19 PM

JS Page
-------------------------------------------------------------------
function rollDice(){
const numOfDice = [Link]("numOfDice").value;
const diceResult = [Link]("diceResult");
const diceImages = [Link]("diceImages");
const values = [];
const images = [];
for(let i = 0;i<numOfDice;i++){
const value = [Link]([Link]() * 6) + 1;
[Link](value);
[Link](`<img src="images/dice_${value}.png">`);
}
[Link] = `dice: ${[Link](", ")}`;
[Link] = [Link]('');
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
#container{
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-align: center;
font-size: 2rem;
font-weight: bold;
}
button{
font-size: 1.5rem;
padding: 10px 15px;
border-radius: 10px;
border: none;
background-color: lawngreen;
color: white;
font-weight: bold;
cursor: pointer;
}
button:hover{
background-color: rgb(55, 255, 55);
}
button:active{
background-color: rgb(101, 255, 101);
}
input{
font-size: 2rem;
width: 150px;
text-align: center;
font-weight: bold;
}
#diceResult{
margin: 25px;
}

JavaScript Page 45
}
#diceImages img{
width: 150px;
height: 150px;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Dice Roller Program</title>
</head>
<body>
<div id="container">
<h1>Dice Roller</h1>
<label># of dice:</label>
<input type="number" id="numOfDice"value="1" min="1">
<button Dice</button>
<div id="diceResult"></div>
<div id="diceImages"></div>
</div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 46
Random Password generator
Monday, July 21, 2025 9:19 PM

JS Page
-------------------------------------------------------------------
function
generatePassword(length,includeLowercase,includeUppercase,includeNum
bers,includeSymbols){
const lowercaseChars = "abcdefghijklmnopqrstuvwxyz";
const uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXY";
const numberChars = "0123456789";
const symbolChars = "!@#$%^&*()_+-=/";
let allowedChars = "";
let passwords = "";
allowedChars += includeLowercase ? lowercaseChars : "";
allowedChars += includeUppercase ? uppercaseChars : "";
allowedChars += includeNumbers ? numberChars : "";
allowedChars += includeSymbols ? symbolChars : "";
if(length <= 0 ){
return `(password length must be atleast 1)`;
}
if([Link] === 0){
return `(At least 1 set of characters needs to be selected)`;
}
for(let i = 0;i<length;i++){
const randomIndex = [Link]([Link]() *
[Link]);
passwords += allowedChars[randomIndex];
}
return passwords;
}
const passwordLength = 12;
const includeLowercase = true;
const includeUppercase = true;
const includeNumbers = true;
const includeSymbols = true;
const password = generatePassword(passwordLength,
includeLowercase,
includeUppercase,
includeNumbers,
includeSymbols);
[Link](`Generated password: ${password}`);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Random Password Generator</title>
</head>

JavaScript Page 47
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 48
CallBacks
Monday, July 21, 2025 9:19 PM

A function that is passed as an argument to another function used to


handle asychronous operations:

1. Reading a file

2. Network requests

3. Interacting with databases

"Hey, when you're done, call this next."

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
hello(wait);
function hello(callBack){
[Link]("Hello!");
callBack();

}
function goodbye(){
[Link]("Goodbye!");
}
function leave(){
[Link]("Leave!");
}
function wait(){
[Link]("Wait!");
}
sum(displayPage,1,2);
function sum(callBack,x,y){
let result = x + y;
callBack(result);
}
function displayConsole(result){
[Link](result);
}
function displayPage(result){
[Link]("myH1").textContent = result;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Call backs</title>

JavaScript Page 49
<title>Call backs</title>
</head>
<body>
<h1 id="myH1"></h1>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 50
forEach()
Monday, July 21, 2025 9:19 PM

Method used to iterate over the elements of an array and apply a


specified function (callback) to each element

Behind the scenes the forEach() will provide a element,index,array


are provided.

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let numbers = [1,2,3,4,5];
[Link](double);
[Link](display);
[Link]("");
[Link](triple);
[Link](display);
[Link]("");
[Link](square);
[Link](display);
[Link]("");
[Link](cubed);
[Link](display);
function double(element,index,array){
array[index] = element * 2;
}
function triple(element,index,array){
array[index] = element * 3;
}
function square(element,index,array){
array[index] = [Link](element,2);
}
function cubed(element,index,array){
array[index] = [Link](element,3);
}
function display(element){
[Link](element);
}

let fruits = ["apple","orange","banana","coconut"];


[Link]("");
[Link](displayFruit);
[Link]("");
[Link](upperCase);
[Link](displayFruit);
[Link]("");
[Link](lowerCase);
[Link](displayFruit);
[Link]("");
[Link](capitalize);
[Link](displayFruit);

JavaScript Page 51
function upperCase(element,index,array){
array[index] = [Link]();
}
function lowerCase(element,index,array){
array[index] = [Link]();
}
function capitalize(element,index,array){
array[index] = [Link](0).toUpperCase() +
[Link](1).toLowerCase();
}
function displayFruit(element){
[Link](element);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>For Each</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 52
map()
Monday, July 21, 2025 9:19 PM

Accepts a callback and applies that function to each element of an


array, then return a new array

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const numbers = [1,2,3,4,5];
const squares = [Link](square);
[Link](squares);
const cubed = [Link](cube);
[Link](cubed);
function square(element){
return [Link](element,2);
}
function cube(element){
return [Link](element,3);
}
const students = ["Alice","Tom","Jerry","Bob"];
const studentsUpper = [Link](upperCase);
[Link](studentsUpper);
const studentsLower= [Link](lowerCase);
[Link](studentsLower);
function upperCase(element){
return [Link]();
}
function lowerCase(element){
return [Link]();
}

const dates = ["2024-1-10","2025-2-20","2026-3-30"];


const formattedDates = [Link](formatDates);
[Link](formattedDates);
function formatDates(element){
const parts = [Link]("-");
return `${parts[2]}/${parts[1]}/${parts[0]}`;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Map</title>
</head>
<body>
<script src="[Link]"></script>
</body>

JavaScript Page 53
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 54
filter()
Monday, July 21, 2025 9:19 PM

Creates a new array by filtering out elements

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let numbers = [1,2,3,4,5,6,7]
let evenNums = [Link](isEven);
let oddNums = [Link](isOdd);
[Link](evenNums);
[Link](oddNums);
function isEven(element){
return element % 2 === 0;
}
function isOdd(element){
return element % 2 !== 0;
}
const age = [16,17,18,18,19,20,60];
const adult = [Link](isAdult);
const children = [Link](isChild);
[Link](adult);
[Link](children);
function isAdult(element){
return element >= 18;
}
function isChild(element){
return element < 18;
}
const words =
["apple","orange","banana","kiwi","pomegranate","coconut"];
const shortWords = [Link](getShortWords);
const longWords = [Link](getLongWords);
[Link](shortWords);
[Link](longWords);
function getShortWords(element){
return [Link] <= 6;
}
function getLongWords(element){
return [Link] > 6;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Filter</title>
</head>

JavaScript Page 55
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 56
reduce()
Monday, July 21, 2025 9:19 PM

Reduce the elements of an array to a single value

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const prices = [5,30,63,25,10,15,20];
const total = [Link](sumTotal);
[Link](`$${[Link](2)}`);
function sumTotal(previous,next){
return previous + next;
}
const grades = [75,50,90,80,65,95];
const maxGrade = [Link](getMax);
const minGrade = [Link](getMin);
[Link](maxGrade);
[Link](minGrade);
function getMax(previous,next){
return [Link](previous,next);
}
function getMin(previous,next){
return [Link](previous,next);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Reduce</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 57
Function expressions
Monday, July 21, 2025 9:20 PM

A way to define functions as values or variables

Function declaration = define a reusable block of code that performs


a specific task

Function expression is used in Callbacks in asynchronous operations,


Higher order functions, Closures, Event Listeners

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//Function declaration
// function hello(){
// [Link]("Hello");
// }
//Function Expression
const hello = function(){
[Link]("hello");
}
hello();
setTimeout(function(){
[Link]("hello");
},3000);
const numbers = [1,2,3,4,5,6];
const squares = [Link](function(element){
return [Link](element,2);
});
[Link](squares);
const cubes = [Link](function(element){
return [Link](element,3);
})
[Link](cubes);
const evenNums = [Link](function(element){
return element % 2 === 0;
})
[Link](evenNums);
const oddNums = [Link](function(element){
return element % 2 !== 0;
})
[Link](oddNums);
const total = [Link](function(previous,next){
return previous + next;
})
[Link](total);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>

JavaScript Page 58
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Function Expression</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 59
Arrow Functions
Monday, July 21, 2025 9:20 PM

A concise way to write function expressions good for simple


functions that you use only once (parameters) => some code

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//using func declaration
// function hello(){
// [Link]("Hello")
// }
// hello();
//using func expression
// const hello = function(){
// [Link]("Hello")
// }
// hello();
//using arrow func
const hello = (name,age) => {
[Link](`Hello ${name}`)
[Link](`You are ${age} years old`)
};
hello("Tyler",18);
setTimeout(() => [Link]("Hello"),
3000);
const numbers = [1,2,3,4,5,6];
const squares = [Link]((element) => [Link](element,2));
[Link](squares);
const cubes = [Link]((element) => [Link](element,3));
[Link](cubes);
const evenNums = [Link]((element) => element % 2 === 0);
[Link](evenNums);
const oddNums = [Link]((element) => element % 2 !== 0);
[Link](oddNums);
const total = [Link]((previous,next) => previous + next);
[Link](total);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Arrow Function</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 60
JavaScript Objects
Monday, July 21, 2025 9:20 PM

A collection of related properties and/or methods. Can represent


real world objects (people, products, places).

Object = {key:value,function()}

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const person1 = {
firstName: "Tyler",
lastName: "Katsha",
age: 18,
isAlive: true,
isEmployed: false,
isStudent: true,
sayHello: () => [Link](`Hello I'm ${[Link]}`),
eat: (food) => [Link](`I am eating ${food}`),
}
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]("chicken");
const person2 = {
firstName: "Bob",
lastName: "Jeff",
age: 67,
isAlive: false,
isEmployed: true,
isStudent: true,
sayHello: () => [Link](`Hello I'm ${[Link]}`),
eat: (food) => [Link](`I am eating ${food}`),
}
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]("fish");
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>JS Objects</title>
</head>
<body>

JavaScript Page 61
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 62
What is THIS
Monday, July 21, 2025 9:20 PM

Reference to the object where THIS is used (the object depends on


the immediate context)

[Link] = [Link]

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const person1 = {
name: "Spongbob",
favFood: "hamburgers",
sayHello: function(){[Link](`Hello I am ${[Link]}`)},
eat: function(){ [Link](`${[Link]} is eating
${[Link]}`)}
}
[Link]();
[Link]();
const person2 = {
name: "Patrick",
favFood: "pizza",
sayHello: function(){[Link](`Hello I am ${[Link]}`)},
eat: function(){ [Link](`${[Link]} is eating
${[Link]}`)}
}
[Link]();
[Link]();
[Link](this);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>THIS</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 63
Constructors
Monday, July 21, 2025 9:20 PM

A special method for defining the properties and methods of objects

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
function Car(make,model,year,color){
[Link] = make,
[Link] = model,
[Link] = year,
[Link] = color,
[Link] = function(){ [Link](`You drive the
${[Link]}`)}
}
const car1 = new Car("Ford","Mustang",2024,"red");
const car2 = new Car("Chevrolet","Camero",2025,"blue");
const car3 = new Car("Dodge","Charger",2026,"silver");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]("");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]("");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]();
[Link]();
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Constructor</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 64
Classes
Monday, July 21, 2025 9:20 PM

(ES6 Feature) provides a more structured and cleaner way to work


with objects compared to traditional constructor functions

[Link] keyword, encapsulation, inheritance, etc.

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
class Products{
constructor(name,price){
[Link] = name;
[Link] = price;
}
displayProduct(){
[Link](`Product: ${[Link]}`);
[Link](`Price: $${[Link](2)}`);
}
calculateTotal(salesTax){
return [Link] + ([Link] * salesTax);
}
}
const salesTax = 0.05;
const product1 = new Products("Shirt",19.99);
const product2 = new Products("Pants",22.50);
const product3 = new Products("Underwear",100);
[Link]();
[Link]();
[Link]();
const total1 = [Link](salesTax);
[Link](`Total price (with tax): $${[Link](2)}`);
const total2 = [Link](salesTax);
[Link](`Total price (with tax): $${[Link](2)}`);
const total3 = [Link](salesTax);
[Link](`Total price (with tax): $${[Link](2)}`);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Classes</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 65
STATIC keyword
Monday, July 21, 2025 9:27 PM

Keyword that defines properties or methods that belong to a class


itself rather than the objects created from that class (class owns
anything static, not the objects)

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
class MathUtil{
static PI = 3.14159;
static getDiameter(radius){
return radius * 2;
}
static getCircumference(radius){
return 2 * [Link] * radius;
}
static getArea(radius){
return [Link] * [Link](radius,2);
}
}
[Link]([Link]);
[Link]([Link](10));
[Link]([Link](10));
[Link]([Link](10));
class User{
static userCount = 0;
constructor(name){
[Link] = name;
[Link]++;
}
static getUserCount(){
[Link](`There are ${[Link]} users online`);
}
sayHello(){
[Link](`Hello my username is ${[Link]}`);
}
}
const user1 = new User("Jeff");
const user2 = new User("Bob");
const user3 = new User("Tom");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]();
[Link]();
[Link]();
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>

JavaScript Page 66
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>STATIC</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 67
Inheritance
Monday, July 21, 2025 9:27 PM

Allows a new class to inherit properties and methods from an


existing class (parent -> child) helps with code reusability

Inheritance helps us follow the DRY princple --> Don’t Repeat


Yourself

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
class Animal{
isAlive = true;
eat(){
[Link](`This ${[Link]} is eating`);
}
sleep(){
[Link](`This ${[Link]} is sleeping`);
}
}
class Rabbit extends Animal{
name = "Rabbit";
run(){
[Link](`This ${[Link]} is running`);
}
}
class Fish extends Animal{
name = "Fish";
swim(){
[Link](`This ${[Link]} is swimming`);
}
}
class Hawk extends Animal{
name = "Hawk";
fly(){
[Link](`This ${[Link]} is flying`);
}

}
const rabbit = new Rabbit();
const fish = new Fish();
const hawk = new Hawk();

[Link] = false;

//Animal class isAlive attribute


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

//Animal class eat method


[Link]();

JavaScript Page 68
[Link]();
[Link]();
[Link]();

//Animal class sleep method


[Link]();
[Link]();
[Link]();

//Animals that inherits Animal class and have unique methods


[Link]();
[Link]();
[Link]();
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Inheritance</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 69
SUPER keyword
Monday, July 21, 2025 9:27 PM

Keyword is used in classes to call the constructor or access the


properties and methods of a parent (superclass)

this = this object

super = the parent

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
class Animal{
constructor(name,age){
[Link] = name;
[Link] = age;
}
move(speed){
[Link](`The ${[Link]} moves at a speed of ${speed}mph`);
}
}
class Rabbit extends Animal{
constructor(name,age,runSpeed){
super(name,age);
[Link] = runSpeed;
}
run(){
[Link](`The ${[Link]} can run`);
[Link]([Link]);
}
}
class Fish extends Animal{
constructor(name,age,swimSpeed){
super(name,age);
[Link] = swimSpeed;
}
swim(){
[Link](`The ${[Link]} can swim`);
[Link]([Link]);
}
}
class Hawk extends Animal{
constructor(name,age,flySpeed){
super(name,age);
[Link] = flySpeed;
}
fly(){
[Link](`The ${[Link]} can fly`);
[Link]([Link]);
}
}

JavaScript Page 70
const rabbit = new Rabbit("rabbit",1,25);
const fish = new Fish("fish",2,25);
const hawk = new Hawk("hawk",3,25);

[Link]("---Rabbit details---");
[Link](`Name: ${[Link]}`);
[Link](`Age: ${[Link]}`);
[Link](`Run speed: ${[Link]}`);
[Link]("");

[Link]("---Fish details---");
[Link](`Name: ${[Link]}`);
[Link](`Age: ${[Link]}`);
[Link](`swim speed: ${[Link]}`);
[Link]("");

[Link]("---Hawk details---");
[Link](`Name: ${[Link]}`);
[Link](`Age: ${[Link]}`);
[Link](`fly speed: ${[Link]}`);
[Link]("");

[Link]("---Unique methods---");

[Link]();
[Link]("");

[Link]();
[Link]("");

[Link]();
[Link]("");
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>SUPER</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 71
GETTERS & SETTERS
Monday, July 21, 2025 9:27 PM

Getters = Methods that make a field READABLE.


Setters = Methods that make a field WRITEABLE.

Validate and modify a value when reading/writing a property

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
class Rectangle{
constructor(width,height){
[Link] = width;
[Link] = height;
}
set width(newWidth){
if(newWidth > 0){
this._width = newWidth;
}
else{
[Link]("Width must be a positive number");
}
}
set height(newHeight){
if(newHeight > 0){
this._height = newHeight;
}
else{
[Link]("Height must be a positive number");
}
}
get width(){
return `${this._width.toFixed(1)}cm`;
}
get height(){
return `${this._height.toFixed(1)}cm`;
}
get area(){
return `${(this._width * this._height).toFixed(1)}cm^2`;
}
}

const rectangle = new Rectangle(3,4);

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

class Person{
constructor(firstname,lastname,age){
[Link] = firstname;
[Link] = lastname;

JavaScript Page 72
[Link] = lastname;
[Link] = age;
}
set firstname(newFirstName){
if(typeof newFirstName === "string" && [Link] > 0){
this._firstname = newFirstName;
}
else{
[Link]("First name must be a non-empty string");
}
}
set lastname(newLastName){
if(typeof newLastName === "string" && [Link] > 0){
this._lastname = newLastName;
}
else{
[Link]("Last name must be a non-empty string");
}
}
set age(newAge){
if(typeof newAge === "number" && newAge >= 0){
this._age = newAge;
}
else{
[Link]("Age must be a non-negative number");
}
}
get firstname(){
return this._firstname;
}
get lastname(){
return this._lastname;
}
get age(){
return this._age;
}
get fullname(){
return this._firstname + " " +this._lastname;
}
}

const person = new Person("Spongebob","Squarepants",30);

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=

JavaScript Page 73
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>GETTERS & SETTERS</title>
</head>
<body>
<script src="GET&[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 74
Destructuring
Monday, July 21, 2025 9:27 PM

Extract values from arrays and objects, then assign them to


variables in a convenient way.

[] = to perform array destructuring


{} = to perform object destructuring

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//-------Example 1-------
//SWAP THE VALUE OF TWO VARIABLES

let a = 1;
let b = 2;

[a,b] = [b,a];

[Link](a);
[Link](b);
[Link]("");

//-------Example 2-------
//SWAP 2 ELEMENTS IN AN ARRAY

const colors = ["red","green","blue","black","white"];

[colors[0],colors[[Link] - 1]] = [colors[[Link] -


1],colors[0]];

[Link](colors);
[Link]("");

//-------Example 3-------
//ASSIGN ARRAY ELEMENTS TO VARIABLES

const colors1 = ["red","green","blue","black","white"];

const [firstcolor,secondcolor,thirdcolor, ...extraColors] = colors1;

[Link](firstcolor);
[Link](secondcolor);
[Link](thirdcolor);
[Link](extraColors);
[Link]("");

//-------Example 4-------
//EXTRACT VALUES FROM OBJECTS

const person1 = {
firstname: "Spongebob",

JavaScript Page 75
firstname: "Spongebob",
lastname: "Squarepants",
age: 30,
job: "Fry Cook",
}

const person2 = {
firstname: "Patrick",
lastname: "Star",
age: 37,
}

// const {firstname,lastname,age,job} = person1;


// [Link](firstname);
// [Link](lastname);
// [Link](age);
// [Link](job);
// [Link]("");

// const {firstName,lastName,age,job="Unemployeed"} = person2;


// [Link](firstName);
// [Link](lastName);
// [Link](age);
// [Link](job);

//-------Example 5-------
//DESTRUCTURE IN FUNCTION PARAMETERS

function displayaPerson({firstname,lastname,age,job="Unemployeed"}){

[Link](firstname);
[Link](lastname);
[Link](age);
[Link](job);

[Link]("");
}

displayaPerson(person1);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Destructuring</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 76
-------------------------------------------------------------------

JavaScript Page 77
Nested objects
Monday, July 21, 2025 9:27 PM

Objects inside of other objects.

Allows you to represent more complex data structures. Child Object


is enclosed by a Parent Object

Person{Address{}, ContactInfo{}}
ShoppingCart{Keyboard{}, Mouse{}, Monitor{}}

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const person = {
fullName: "Spongebob Squarepants",
age: 30,
isStudent: true,
hobbies: ["Karate","jellyfishing","cooking"],
address: {
street: "1234 Conch St.",
city: "Bikini Bottom",
country: "Int. Water"
},
}

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
for(const property in [Link]){
[Link]([Link][property]);
}
[Link]("");

class Address{
constructor(street,city,country){
[Link] = street;
[Link] = city;
[Link] = country;
}
}

class Person{
constructor(name,age,...address){
[Link] = name;
[Link] = age;
[Link] = new Address(...address);
}
}

const person1 = new Person("Spongebob", 30, "124 Conch St",


"Binkini Bottom",

JavaScript Page 78
"Binkini Bottom",
"Int. Water")

const person2 = new Person("Patrick", 37, "128 Conch St",


"Binkini Bottom",
"Int. Water")

const person3 = new Person("Squidward", 45, "126 Conch St",


"Binkini Bottom",
"Int. Water")

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>NestObj</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 79
Array of objects
Monday, July 21, 2025 9:28 PM

JS Page
-------------------------------------------------------------------
const fruits = [{name:"apple",color:"red",calories:98},
{name:"orange",color:"orange",calories:45},
{name:"banana",color:"yellow",calories:105},
{name:"coconut",color:"white",calories:159},
{name:"pineapple",color:"yellow",calories:37}]

//[Link]();

[Link]({name:"grapes",color:"purple",calories:62});

[Link](fruits);

[Link](1,2);
[Link](fruits);

// ------- forEach() -------

[Link](fruits => [Link]([Link]));


[Link](fruits => [Link]([Link]));
[Link](fruits => [Link]([Link]));

// ------- map() -------

const fruitsName = [Link](fruits => [Link]);


const fruitsColor = [Link](fruits => [Link]);
const fruitCalories = [Link](fruits => [Link]);

[Link](fruitsName);
[Link](fruitsColor);
[Link](fruitCalories);
// ------- filter() -------

const yellowFruits = [Link](fruit => [Link] ===


"yellow");
const lowCal = [Link](fruit => [Link] < 100);
const highCal = [Link](fruit => [Link] >= 100);

[Link](yellowFruits);
[Link](lowCal);
[Link](highCal);
// ------- reduce() -------

const MaxFruit = [Link]((max,fruit) => [Link] >=


[Link] ? fruit : max);
const minFruit = [Link]((min,fruit) => [Link]
< [Link] ? fruit : min);

[Link](MaxFruit);

JavaScript Page 80
[Link](MaxFruit);
[Link](minFruit);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Arrays of Objects</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 81
Sorting
Monday, July 21, 2025 9:28 PM

Method used to sort elements of an array in place. Sorts elements as


strings in lexicographic order, not alphabetical

lexicographic = (alphabet + number + symbols) as strings

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let fruits = ["apple","orange","banana","coconut","pinapple"];

[Link]();

[Link](fruits);

let numbers = [1,10,2,9,3,8,4,7,5,6];

//from 1-10
[Link]((a,b) => a - b);

//from 1-10
[Link]((a,b) => b - a);
[Link](numbers);

const people = [{name: "Spongebob",age:30,gpa:3.0},


{name: "Patrick",age:37,gpa:1.5},
{name: "Squidward",age:51,gpa:2.5},
{name: "Sandy",age:27,gpa:4.0}];

//from youngest to oldest comparing age


[Link]((a,b) => [Link] - [Link]);

//from oldest to youngest comparing age


[Link]((a,b) => [Link] - [Link]);

//from lowest to highest comparing gpa


[Link]((a,b) => [Link] - [Link]);

//from highest to lowest comparing gpa


[Link]((a,b) => [Link] - [Link]);

[Link]((a,b) => [Link]([Link]));

//reversing the order of the names


[Link]((a,b) => [Link]([Link]));

[Link](people);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>

JavaScript Page 82
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Sorting</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 83
Shuffling an Array
Monday, July 21, 2025 9:28 PM

JS Page
-------------------------------------------------------------------
const cards = ['A',2,3,4,5,6,7,8,9,10,'J','Q','K'];
//Not recommended way to sort the array
// [Link](() => [Link]() - 0.5);
// [Link](cards);
//Use the Fisher Yates algorithm
shuffle(cards);
[Link](cards);
function shuffle(array){
for(let i = [Link] - 1; i > 0;i--){
const random = [Link]([Link]() * (i+1));
[array[i],array[random]] = [array[random],array[i]];
}
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Shuffling an Array</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 84
Dates
Monday, July 21, 2025 9:28 PM

Objects that contain values that represent dates and times. These
data objects can be changed and formatted

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//Date(year,month,day,hour,minute,second,ms)
// const date = new Date(2024,0,1,2,3,4,5);

//String representation of time


// const date = new Date("2024-01-02T12:00:00Z");
//another format
const date = new Date();
const year = [Link]();
[Link](year);
const month = [Link]();
[Link](month);
const day = [Link]();
[Link](day);
const hour = [Link]();
[Link](hour);
const minutes = [Link]();
[Link](minutes);
const seconds = [Link]();
[Link](seconds);
const dayOfWeek = [Link]();
[Link](dayOfWeek);

[Link](2024);
[Link](1);
[Link](23);
[Link](14);
[Link](50);
[Link](23);
[Link](date);
const date1 = new Date("2023-12-31");
const date2 = new Date("2024-01-01");
if(date2 > date1){
[Link]("Happy new Year");
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Dates</title>

JavaScript Page 85
<title>Dates</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 86
Closures
Monday, July 21, 2025 9:31 PM

A function defined inside of another function, the inner function


has access to the variables and scope of the outerfunction. Allow
for private variables and state maintence. Used frequently in JS
frameworks: React, Vue, Angular

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
function outer(){
let msg = "Hello";
function inner(){
[Link](msg);
}
inner();
}
outer();

function createACounter(){
let count = 0;
function increment(){
count++;
[Link](`Count increased to ${count}`);
}
function getCount(){
return count;
}
return {increment,getCount};
}
const counter = createACounter();
[Link]();
[Link]();
[Link]();
[Link](`The current count is ${[Link]()}`);

function createGame(){
let score = 0;
function increaseScore(points){
score += points;
[Link](`+${points}pts`);
}
function decreaseScore(points){
score -= points;
[Link](`-${points}pts`);
}
function getScore(){
return score;
}
return {increaseScore,decreaseScore,getScore};
}
const game = createGame();

JavaScript Page 87
const game = createGame();

[Link](50);
[Link](30);
[Link](20);
[Link](`The final score is ${[Link]()}pts`);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Closures</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 88
setTimeout()
Monday, July 21, 2025 9:31 PM

Function in javascript that allow you to schedule the execution of a


function after an amount of time (milliseconds). Times are
approximate (varies based on the workload of the JavaScript runtime
env.)

setTimeout(callBack,delay);

clearTimeout(timeoutId) = can cancel a timeout before it triggers

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// function sayHello(){
// [Link]("Hello");
// }
// setTimeout(sayHello,3000);
// setTimeout(function(){
// [Link]("Hello1");
// },3000);
// setTimeout(() => [Link]("Hello2"),3000);
// const timeoutID = setTimeout(() => [Link]("Hello3"),3000);
// clearTimeout(timeoutID);
let timeoutId;
function startTimer(){
timeoutId = setTimeout(() => [Link]("Hello"),3000);
[Link]("STARTED");
}
function clearTimer(){
clearTimeout(timeoutId);
[Link]("CLEARED");
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>setTimeout()</title>
</head>
<body>
<button > <button > <script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 89
Digital Clock Program
Monday, July 21, 2025 9:31 PM

JS Page
-------------------------------------------------------------------
function updateClock(){
const now = new Date();
let hours = [Link]();
const mardiem = hours >= 12 ? "PM" : "AM";
hours = hours % 12 || 12;
hours = [Link]().padStart(2,0);
const minutes = [Link]().toString().padStart(2,0);
const seconds = [Link]().toString().padStart(2,0);
const timeString = `${hours}:${minutes}:${seconds} ${mardiem}`;
[Link]("clock").textContent = timeString;

}
updateClock();
setInterval(updateClock,1000);
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
margin: 0;
}
#clock-container{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#clock{
font-family: monospace;
font-size: 6.5rem;
font-weight: bold;
text-align: center;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Digital clock program</title>
</head>
<body>
<div id="clock-container">
<div id="clock">00:00:00</div>

JavaScript Page 90
<div id="clock">00:00:00</div>
</div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 91
Stopwatch Program
Monday, July 21, 2025 9:31 PM

JS Page
-------------------------------------------------------------------
const display = [Link]("stopwatch");
let timer = null;
let startTime = 0;
let elapsedTime = 0;
let isRunning = false;
function start(){
if(!isRunning){
startTime = [Link]() - elapsedTime;
timer = setInterval(update,10);
isRunning = true;
}
}
function stop(){
if(isRunning){
clearInterval(timer);
elapsedTime = [Link]() - startTime;
isRunning = false;
}
}
function reset(){
clearInterval(timer);
startTime = 0;
elapsedTime = 0;
isRunning = false;
[Link] = "00:00:00:00";
}
function update(){
const currentTime = [Link]();
elapsedTime = currentTime - startTime;
let hours = [Link](elapsedTime / (1000 * 60 * 60));
let minutes = [Link](elapsedTime / (1000 * 60) % 60);
let seconds = [Link](elapsedTime/1000 % 60);
let milliseconds = [Link](elapsedTime % 1000 / 10);
hours = [Link]().padStart(2,"0");
minutes = [Link]().padStart(2,"0");
seconds = [Link]().padStart(2,"0");
milliseconds = [Link]().padStart(2,"0");
[Link] = `${hours}:${minutes}:${seconds}:
${milliseconds}`;
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
margin:0;
background-color: gainsboro;
font-family: Arial, Helvetica, sans-serif;
}

JavaScript Page 92
}
#title{
font-size: 5rem;
text-align: center;
color: rgb(80, 73, 73);
}
#stopwatch-container{
border: 4px solid black;
background-color: white;
margin: auto;
padding: 5rem 5rem;
width: 60%;
border-radius: 3.5rem;
display: flex;
justify-content: center;
justify-items: center;
align-items: center;
flex-wrap: wrap;
flex-direction: column;
}
#stopwatch{
font-size: 5rem;
}
#start,#stop,#reset{
width: 10rem;
height: 4rem;
margin: 1rem 1rem;
border-radius: 1rem;
border: none;
font-size: 2em;
color: white;
cursor: pointer;
transition: background-color 0.15s;
}
#start{
background-color: rgb(32, 189, 32);
}
#stop{
background-color: red;
}
#reset{
background-color: rgb(41, 180, 226);
}
#start:hover{
background-color: rgba(32, 189, 32,.8);
}
#stop:hover{
background-color: rgba(255, 0, 0,.8);
}
#reset:hover{
background-color: rgba(41, 180, 226,.8);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------

JavaScript Page 93
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Stopwatch program</title>
</head>
<body>
<div id="title">
<p>Stopwatch</p>
</div>
<div id="stopwatch-container">
<div id="stopwatch">00:00:00:00</div>
<div class="buttons">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
</div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 94
ES6 Modules
Monday, July 21, 2025 9:31 PM

An external file that contains reusable code that can be imported


into other javascript file. Write reusable code for many different
apps. Can contain variables, classes, functions, … and more.
Introduced as part of ECMAScript 2015 update.

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
import {PI, getArea, getCircumference, getVolume} from
'./[Link]';
[Link](PI);
const circumference = getCircumference(10);
const area = getArea(5);
const volume = getVolume(5);
[Link](`Circumference: ${[Link](2)}cm`);
[Link](`Volume: ${[Link](2)}cm^3`);
[Link](`Area: ${[Link](2)}cm^2`);
-------------------------------------------------------------------
Import JS Page
-------------------------------------------------------------------
export const PI = 3.14159;
export function getCircumference(radius){
return 2 * PI * radius;
}
export function getArea(radius){
return PI * [Link](radius,2);
}
export function getVolume(radius){
return (4/3) * PI * [Link](radius,3);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>ES6 modules</title>
</head>
<body>
<script type="module" src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 95
Asynchronous code
Monday, July 21, 2025 9:31 PM

Synchronous - Executes line by line consecutively in a sequential


manner. Code that waits for an operation to complete

Asynchronous - Allows multiple operations to be performed


concurrently without waiting. Doesn't block the execution flow and
allows the program to continue (I/O Operations, network requestsm
fetching data) Handled with: callbacks, promises, Async/Await.

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//Synchronous code
// [Link]("Task 1");
// [Link]("Task 2");
// [Link]("Task 3");
function func1(callback){
setTimeout(() => {[Link]("Task 1");
callback()},3000);
}
function func2(){
[Link]("Task 2");
[Link]("Task 3");
[Link]("Task 4");
}
func1(func2);
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Asynchronous</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 96
Error handling
Monday, July 21, 2025 9:31 PM

An object that is created to represent a problem that occurs. Occur


often with user input or establishing a connection.

try {} - Encloses code that might potentially cause an error


catch {} - Catch and handle any thrown errors from try {}
finally {} - (optional) Always executes. Used mostly for clean up
ex. Close files, close connections, release resources

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
try{
[Link]("Hello");
//NETWORK ERRORS
//PROMISE REJECTIONS
//SECURITY ERRORS
}
catch(error){
[Link](error);
}
finally{
//CLOSE FILES
//CLOSE CONNECTIONS
//RELEASE RESOURCES
[Link]("This always executes");
}
try{
const dividend = [Link]("Enter a dividend: ");
const divisor = [Link]("Enter a divisor: ");

if(divisor == 0){
throw new Error("YOU CAN'T DIVIDE BY ZERO!!!");
}
if(isNaN(dividend) || isNaN(divisor)){
throw new Error("VALUES MUST BE A NUMBER");
}
const result = dividend/divisor;
[Link](result);
}
catch(error){
[Link](error);
}
[Link]("You have reached the end!!");
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

JavaScript Page 97
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>ErrorHandling</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 98
Calculator Program
Monday, July 21, 2025 9:31 PM

JS Page
-------------------------------------------------------------------
const display = [Link]("display");

function appendToDisplay(input){
[Link] += input;
}
function clearDisplay(){
[Link] = "";
}
function calculate(){
/*Executing JavaScript from a string is an enormous security risk.
It is far too easy for a bad actor to run arbitary code when you
use eval().*/
try{
[Link] = eval([Link]);
}
catch(error){
[Link] = "Erorr";
}
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: hsl(0,0%,95%);
}
#calculator{
font-family: Arial, Helvetica, sans-serif;
background-color: hsl(0,0%,15%);
border-radius: 15px;
max-width: 500px;
overflow: hidden;
}
#display{
width: 100%;
padding: 20px;
font-size: 5rem;
text-align: left;
border: none;
background-color: hsl(0,0%,20%);
color: white;
}
#keys{
display: grid;

JavaScript Page 99
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
padding: 25px;
}
button{
width: 100px;
height: 100px;
border-radius: 50px;
border: none;
background-color: rgb(77, 77, 77);
color: white;
font-size: 3rem;
font-weight: bold;
cursor: pointer;
transition: background-color 0.15s;
}
button:hover{
background-color: hsl(0,0%,40%);
}
button:active{
background-color: hsl(0,0%,50%);
}
.operator-btn{
background-color: hsl(35, 100%, 55%);
}
.operator-btn:hover{
background-color: hsl(35, 100%, 65%);
}
.operator-btn:active{
background-color: hsl(35, 100%, 75%);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Calculator Program</title>
</head>
<body>
<div id="calculator">
<input id="display" readonly>
<div id="keys">
<button class="operator-
btn">+</button>
<button > <button > <button > <button class="operator-btn">-
</button>

JavaScript Page 100


</button>
<button > <button > <button > <button class="operator-
btn">*</button>
<button > <button > <button > <button class="operator-
btn">/</button>
<button > <button > <button > <button class="operator-btn">
C</button>
</div>
</div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 101


What is the DOM?
Monday, July 21, 2025 9:31 PM

DOM = DOCUMENT OBJECT MODEL

Object{} that represents the page you see in the web browser and
provides you with an API to interact with it. Web browsers
constructs the DOM when it loads an HTML document, and structures
all the elements in a tree-like representation. Javascript can
access the DOM to dynamically change the content, structure, and
style of a web page.

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// [Link](document);
// [Link] = "My website";
// [Link]="hsl(0,0%.15%)";
// [Link](document);
const username = " Tyler";
const welcomeMsg = [Link]("welcome-msg");
[Link] += username === "" ? `Guest`: username;
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

JavaScript Page 102


<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>DOM</title>
</head>
<body>
<h1 id="welcome-msg">Welcome</h1>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 103


Element selectors
Monday, July 21, 2025 9:31 PM

Methods used to target and manipulate HTML elements. They allow you
to select one or multiple HTML elements from the DOM(Document Object
Model)

1. [Link]() ELEMENT OR NULL


2. [Link]() HTML Collection
3. [Link]() HTML Collection
4. [Link]() ELEMENT OR NULL
5. [Link]() NODELIST

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//--[Link]()--
const myHeading = [Link]("my-heading");
[Link] = "yellow";
[Link] = "center";
[Link](myHeading);

//--[Link]()--
const fruits = [Link]("fruits");
[Link](fruits);
// fruits[0].[Link] = "red";
// for(let fruit of fruits){
// [Link] = "red";
// }
// [Link](fruits).forEach(fruit => [Link] =
"yellow");

//--[Link]()--
const h4Elements = [Link]("h4");
const liElements = [Link]("li");
[Link](h4Elements);
h4Elements[0].[Link] = "red";
h4Elements[1].[Link] = "green";
for(let h4Element of h4Elements){
[Link] = "gray";
}
for(let liElement of liElements){
[Link] = "blue";
}
[Link](h4Elements).forEach(h4Element =>
[Link] = "lightGray");
[Link](liElements).forEach(liElement =>
[Link] = "lightGreen");
//--[Link]()--
const element = [Link]("h4");
[Link] = "yellow";
//--[Link]()--
const fruits1 = [Link](".fruits");

JavaScript Page 104


const fruits1 = [Link](".fruits");
fruits1[2].[Link] = "lightGreen";
const foods = [Link]("li");
foods[4].[Link] = "yellow";
[Link](food => [Link] = "green");
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Element Selectors</title>
</head>
<body>
<h1 id="my-heading">Food R Us</h1>
<div class="fruits">Apple</div>
<div class="fruits">Orange</div>
<div class="fruits">Banana</div>
<h4>Root Vegetables</h4>
<ul>
<li>Beats</li>
<li>Carrots</li>
<li>Potatoes</li>
</ul>
<h4>Non-Root Vegetables</h4>
<ul>
<li>Broccoli</li>
<li>Celery</li>
<li>Onions</li>
</ul>
<script src="[Link]"></script>
</body>
<style>
body{
font-size: 1.75rem;
}
</style>
</html>
-------------------------------------------------------------------

JavaScript Page 105


DOM navigation
Monday, July 21, 2025 9:31 PM

The process of navigating through the structure of an HTML document


using Javascript.

.firstElementChild
.lastElementChild
.nextElementSibling
.previousElementSibling
.parentElement
.children

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
//--------------- .firstElementChild ---------------
const fruit = [Link]("fruits");
const vegetable = [Link]("vegetables");
const dessert = [Link]("desserts");

const fruitFirstChild = [Link];


const vegetableFirstChild = [Link];
const dessertFirstChild = [Link];

[Link] = "yellow";
[Link] = "yellow";
[Link] = "yellow";

//Faster to use querySelectorAll than doing one by one


const ulElements = [Link]("ul");
[Link](ulElement => {
const firstChild = [Link];
[Link] = "lightgreen";
})

//--------------- .lastElementChild ---------------


const element = [Link]("fruits");
const lastChild = [Link];
[Link] = "yellow";
const ulElements1 = [Link]("ul");
[Link](ulElement1 => {
const lastChild = [Link];
[Link] = "green";
})

//--------------- .nextElementSibling ---------------


const sibling = [Link]("orange");
const nextSibling = [Link];
[Link] = "yellow";

//--------------- .previousElementSibling ---------------


const sibling1 = [Link]("pie");

JavaScript Page 106


const sibling1 = [Link]("pie");
const previousSibling = [Link];
[Link] = "yellow";

//--------------- .parentElement ---------------


const element1 = [Link]("carrots");
const parent = [Link];
[Link] = "lightgray";

//--------------- .children ---------------


const element2 = [Link]("desserts");
const children = [Link];
[Link](children);
[Link](children).forEach(child =>{
[Link] = "yellow";
})
children[1].[Link] = "lightgreen";
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>DOM Navigation</title>
</head>
<body>
<ul id="fruits">
<li id="apple">Apple</li>
<li id="orange">Orange</li>
<li id="banana">Banana</li>
</ul>
<ul id="vegetables">
<li id="carrots">Carrots</li>
<li id="onions">Onions</li>
<li id="potatoes">Potatoes</li>
</ul>
<ul id="desserts">
<li id="cake">Cake</li>
<li id="pie">pie</li>
<li id="ice-cream">ice cream</li>
</ul>
<script src="[Link]"></script>
</body>
<style>
body{
font-size: 1.75rem;
}
</style>
</html>
-------------------------------------------------------------------

JavaScript Page 107


Add and change HTML
Monday, July 21, 2025 9:31 PM

JS Page
-------------------------------------------------------------------
//-------------- EXAMPLE 1 <h1> --------------
//STEP 1 CREATE THE ELEMENT
//const newH1 = [Link]("h1");
const newListItem = [Link]("li");

//STEP 2 ADD ATTRIBUTES/PROPERTIES


// [Link] = "I like pizza";
// [Link] = "myH1";
// [Link] = "tomato";
// [Link] = "center";
[Link] = "Coconut";
[Link] = "coconut";
[Link] = "bold";
[Link] = "lightgreen";
//STEP 3 APPEND ELEMENT TO DOM
//[Link](newListItem);
//[Link](newListItem);
//[Link]("fruits").prepend(newListItem);
[Link]("fruits").append(newListItem);
const orange = [Link]("orange");
const banana = [Link]("banana");
[Link]("fruits").insertBefore(newListItem,orange);
const olfruits = [Link]("#fruits li");
[Link]("fruits").insertBefore(newListItem,olfruits[
3]);
//[Link](newH1);
//[Link](newH1);
//[Link]("box3").append(newH1);
//[Link]("box1").prepend(newH1);
//const box = [Link]("box4");
//[Link](newH1,box);
// const boxs = [Link](".box");
// [Link](newH1,boxs[1]);
//REMOVE HTML ELEMENT
//[Link]("box1").removeChild(newH1);
[Link]("fruits").removeChild(newListItem);
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
/* .box{
border: 3px solid;
width: 100%;
height: 125px;
} */
#fruits{
border: 3px solid;
font-size: 2rem;
}
-------------------------------------------------------------------

JavaScript Page 108


-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Add and change HTML</title>
</head>
<body>
<!-- <div id="box1" class="box">
<p>Box1</p>
</div>
<div id="box2" class="box">
<p>Box2</p>
</div>
<div id="box3" class="box">
<p>Box3</p>
</div>
<div id="box4" class="box">
<p>Box4</p>
</div> -->
<ol id="fruits">
<li id="apple">Apple</li>
<li id="orange">Orange</li>
<li id="banana">Banana</li>
</ol>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 109


Mouse events
Monday, July 21, 2025 9:31 PM

Listen for specific events to create interactive web pages events:


click, mouseover, mouseout

.addEventListener(event, callback or arrow func or anonymous func);

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const myBox = [Link]("myBox");
const myBtn = [Link]("myBtn");
function changeColor(event){
[Link] = "tomato";
[Link] = "OUCH! ";
}
[Link]("click",changeColor);
[Link]("mouseover",event =>{
[Link] = "yellow";
[Link] = "Don't do it ";
});
[Link]("mouseout",event =>{
[Link] = "lightgreen";
[Link] = "Click me ";
})
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
#myBox{
background-color: lightgreen;
width: 300px;
height: 300px;
font-size: 4.1rem;
font-weight: bold;
display: flex;
align-items: center;
text-align: center;
}
#myBtn{
font-size: 3rem;
cursor: pointer;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">

JavaScript Page 110


1.0">
<title>Mouse Events</title>
</head>
<body>
<div id="myBox">Click me </div>
<button id="myBtn">Click me</button>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 111


Key events
Monday, July 21, 2025 9:31 PM

Listen for specific events to create interactive web pages events:


keydown, keyup

.addEventListener(event, callback or arrow func or anonymous func);

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const myBox = [Link]("myBox");
const moveAmount = 10;
let x = 0;
let y = 0;
[Link]("keydown",event =>{
[Link](`Key down = ${[Link]}`);
[Link] = " ";
[Link] = "tomato";
});
[Link]("keyup",event =>{
[Link](`Key up = ${[Link]}`);
[Link] = " ";
[Link] = "lightgreen";
})
[Link]("keydown",event =>{
[Link]();
if([Link]("Arrow")){
switch([Link]){
case "ArrowUp":
y -= moveAmount;
break;
case "ArrowDown":
y += moveAmount;
break;
case "ArrowLeft":
x -= moveAmount;
break;
case "ArrowRight":
x += moveAmount;
break;
}
[Link] = `${y}px`;
[Link] = `${x}px`;
}
})
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
margin: 0;
}
#myBox{

JavaScript Page 112


#myBox{
background-color: lightgreen;
width: 200px;
height: 200px;
font-size: 7.5rem;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>key Events</title>
</head>
<body>
<div id="myBox"> </div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 113


Hide/Show HTML
Monday, July 21, 2025 9:31 PM

JS Page
-------------------------------------------------------------------
const myBtn = [Link]("hide");
const myImg = [Link]("kali");
[Link]("click",event =>{
if([Link] === "hidden"){
[Link] = "visible";
[Link] = "Hide";
}
else{
[Link] = "hidden";
[Link] = "Show";
}
});
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
#hide{
font-size: 2rem;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>HIDE/SHOW HTML</title>
</head>
<body>
<img id="kali" src="/images/kali linux [Link]"
width="400em" display="block">
<button id="hide">Hide</button>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 114


NodeLists
Monday, July 21, 2025 9:31 PM

Static collection of HTML elements by (id,class,elements)


Can be created by using querySelectorAll()
Similar to an array, but no (map,filter,reduce)
NodeList won't update to automatically reflect changes

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
let buttons = [Link](".myButtons");
[Link](buttons);

//ADD HTML/CSS Properties


// [Link](button =>{
// [Link] = "lightgreen";
// [Link] = "yellow";
// })
//CLICK event listener
// [Link](button =>{
// [Link]("click",event =>{
// [Link] = "tomato";
// });
// });
//MOUSEOVER + MOUSEOUT event listener
[Link](button =>{
[Link]("mouseover",event =>{
[Link] = "hsl(205,100%,40%)";
});
});
[Link](button =>{
[Link]("mouseout",event =>{
[Link] = "hsl(205,100%,60%)";
});
});
//ADD AN ELEMENT
const newBtn = [Link]("button"); //STEP 1
[Link] = "btn5";//STEP 2
[Link] = "myButtons";
[Link](newBtn); //STEP 3
buttons = [Link](".myButtons");
[Link](buttons);
//REMOVE AN ELEMENT
[Link](button =>{
[Link]("click",event =>{
[Link]();
buttons = [Link](".myButtons");
[Link](buttons);
});
});
-------------------------------------------------------------------
CSS Page

JavaScript Page 115


CSS Page
-------------------------------------------------------------------
.myButtons{
font-size: 4rem;
margin: 10px;
border: none;
cursor: pointer;
border-radius: 5px;
padding: 10px 15px;
background-color: hsl(205,100%,60%);
color: white;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Node List</title>
</head>
<body>
<button class="myButtons">btn1</button>
<button class="myButtons">btn2</button>
<button class="myButtons">btn3</button>
<button class="myButtons">btn4</button>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 116


ClassList
Monday, July 21, 2025 9:32 PM

Element property in javascript used to interact with an element's


list of classes (CSS classes). Allows you to make reusable classes
for many elements across your webpage

add()
remove()
toggle(Remove if present,Add if not)
replace(oldClass,newClass)
contains()

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const myBtn = [Link]("myBtn");
const myH1 = [Link]("myH1");

[Link]("enabled");
[Link]("enabled");

[Link]("mouseover",event =>{
[Link]("hover");
});
[Link]("mouseout",event =>{
[Link]("hover");
});
[Link]("enabled");
[Link]("enabled");
[Link]("click",event =>{
if([Link]("disabled")){
[Link] += " ";
}
else{
[Link]("enabled","disabled");
}
});
[Link]("click",event =>{
if([Link]("disabled")){
[Link] += " ";
}
else{
[Link]("enabled","disabled");
}
});
let buttons = [Link](".myBtns");
[Link](button =>{
[Link]("enabled");
});
[Link](button =>{
[Link]("mouseover",event =>{
[Link]("hover");

JavaScript Page 117


[Link]("hover");
});
});
[Link](button =>{
[Link]("mouseout",event =>{
[Link]("hover");
});
});
[Link](button =>{
[Link]("click",event =>{
if([Link]("disabled")){
[Link] += " ";
}
else{
[Link]("enabled","disabled");
}
});
});
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
#myH1{
font-size: 5rem;
}
#myBtn,
.myBtns{
font-size: 4rem;
margin: 10px;
border: none;
border-radius: 5px;
padding: 10px 15px;
}
.enabled{
background-color: hsl(204, 100%, 50%);
color: white;
}
.hover{
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
font-weight: bold;
}
.disabled{
background-color: hsl(0, 0%, 60%);
color: hsl(0, 0%, 80%);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>CLASSLIST</title>

JavaScript Page 118


<title>CLASSLIST</title>
</head>
<body>
<h1 id="myH1">Hello</h1>
<button id="myBtn">My Button</button>
<button class="myBtns">Button 1</button>
<button class="myBtns">Button 2</button>
<button class="myBtns">Button 3</button>
<button class="myBtns">Button 4</button>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 119


Rock, Paper, and Sicossors
Monday, July 21, 2025 9:32 PM

JS Page
-------------------------------------------------------------------
const choices = ["rock","paper","scissors"];
const playerDisplay = [Link]("playerDisplay");
const computerDisplay = [Link]("computerDisplay");
const result = [Link]("result");
const playerScoreDisplay =
[Link]("playerScoreDisplay");
const computerScoreDisplay =
[Link]("computerScoreDisplay");
let playerScore = 0;
let computerScore = 0;
function playGame(playerChoice){

const computerChoice = choices[[Link]([Link]() * 3)];


let cResult = "";
if(playerChoice === computerChoice){
cResult = "IT'S A TIE!";
}
else{
switch(playerChoice){
case "rock":
cResult = computerChoice === "scissors" ? "YOU WIN" : "YOU
LOSE";
break;
case "paper":
cResult = computerChoice === "rock" ? "YOU WIN" : "YOU
LOSE";
break;
case "scissors":
cResult = computerChoice === "paper" ? "YOU WIN" : "YOU
LOSE";
break;
}
}
[Link] = `Player: ${playerChoice}`;
[Link] = `Computer: ${computerChoice}`;
[Link] = cResult;
[Link]("greenText","redText");
switch(cResult){
case "YOU WIN":
[Link]("greenText");
playerScore++;
[Link] = playerScore;
break;

case "YOU LOSE":


[Link]("redText");
computerScore++;
[Link] = computerScore;

JavaScript Page 120


[Link] = computerScore;
break;
}
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
}
h1{
font-size: 3.5rem;
color: hsl(0, 0%, 20%);
}
#choices{
margin-bottom: 30px;
}
#choices button{
font-size: 7.5rem;
min-width: 160px;
background-color: white;
border: none;
background-color: hsl(200,100%,50%);
cursor: pointer;
border-radius: 250px;
transition: background-color 0.15s;
}
#choices button:hover{
background-color: hsl(200,100%,70%);
}
#choices button:active{
background-color: hsl(200,100%,90%);
}
#playerDisplay,#computerDisplay{
font-size: 2.5rem;
}
#result{
font-size: 5rem;
margin: 30px 0;
}
.greenText,
#playerScoreDisplay{
color: hsl(130,84%,54%);
}
.redText,
#computerScoreDisplay{
color: hsl(0,84%,60%);
}
.scoreDisplay{
font-size: 2rem;

JavaScript Page 121


font-size: 2rem;
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>RPS Program</title>
</head>
<body>
<h1>Rock -- Paper --Scissors</h1>
<div id="choices">
<button </button>
<button </button>
<button > </div>
<div id="playerDisplay">PLAYER: </div>
<div id="computerDisplay">COMPUTER: </div>
<div id="result"></div>
<div class="scoreDisplay">Player Score:
<span id="playerScoreDisplay">0</span>
</div>
<div class="scoreDisplay">Computer Score:
<span id="computerScoreDisplay">0</span>
</div>

<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 122


Image Slider
Monday, July 21, 2025 9:32 PM

JS Page
-------------------------------------------------------------------
const slides = [Link](".slides img");
let slideIndex = 0;
let intervalId = null;
// initializeSlider();
[Link]("DOMContentLoaded",initializeSlider);
function initializeSlider(){

if([Link] > 0){


slides[slideIndex].[Link]("displaySlide");
intervalId = setInterval(nextSlide,5000);
}
}
function showSlide(index){
if(index >= [Link]){
slideIndex = 0;
}
else if(index < 0){
slideIndex = [Link] - 1;
}
[Link](slide =>{
[Link]("displaySlide");
})
slides[slideIndex].[Link]("displaySlide");
}
function prevSlide(){
clearInterval(intervalId);
slideIndex--;
showSlide(slideIndex);
}
function nextSlide(){
slideIndex++;
showSlide(slideIndex);
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
.slider{
position: relative;
width: 100%;
margin: auto;
overflow: hidden;
}
.slider img{
width: 100%;
display: none;
}
[Link]{
display: block;

JavaScript Page 123


display: block;
animation-name: fade;
animation-duration: 2s;
}
.slider button{
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 2rem;
padding: 10px 15px;
background-color: rgba(0, 0, 0, 0.5);
border: none;
cursor: pointer;
}
.prev{
left:0;
}
.next{
right:0;
}
@keyframes fade{
from{opacity: .5}
to{opacity: 1;}
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Image Slider</title>
</head>
<body>
<div class="slider">
<div class="slides">
<img class="slide" src="/images/911 GT3 [Link]" alt="Image #
1">
<img class="slide" src="/images/911 GT3 [Link]" alt="Image #
2">
<img class="slide" src="/images/911 GT3 [Link]" alt="Image #
3">
</div>
<button class="prev" > <button class="next" > </div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 124


Callback Hell?
Monday, July 21, 2025 9:32 PM

Situation in JavaScript where callbacks are nested within other


callbacks to the degree where the code is difficult to read. Old
pattern to handle asynchronous functions. Use promises + async/await
to avoid callback Hell

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
function task1(callback){
setTimeout(() =>{
[Link]("Task 1 complete");
callback();
},2000);
}
function task2(callback){
setTimeout(() =>{
[Link]("Task 2 complete");
callback();
},1000);}
function task3(callback){
setTimeout(() =>{
[Link]("Task 3 complete");
callback();
},3000);
}
function task4(callback){
setTimeout(() =>{
[Link]("Task 4 complete");
callback();
},1500);
}
function task5(callback){
setTimeout(() =>{
[Link]("Task 5 complete");
callback();
},1500);
}
task1(()=>{
task2(()=>{
task3(()=>{
task4(()=>{
task5(()=>{
[Link]("All task are complete");
});
});
});
});
});
-------------------------------------------------------------------
HTML Page

JavaScript Page 125


HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>CallBack Hell?</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 126


Promises
Monday, July 21, 2025 9:32 PM

An Object that manages asynchronous operations. Wrap a Promise


object around {asynchronous code} "I promise to return a value"

PENDING -> RESOLVED or REJECTED

new Promise((resolve,reject) => {asynchronous code})

DO THESE CHORES IN ORDER


1. Walk the dog
2. Clean the kitchen
3. Take out the trash

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// function walkDog(callback){
// setTimeout(() =>{
// [Link]("You walk the dog");
// callback();
// },1500);
// }
// function cleanKitchen(callback){
// setTimeout(()=>{
// [Link]("You clean the kitchen");
// callback();
// },2500);
// }
// function takeOutTrash(callback){
// setTimeout(()=>{
// [Link]("You take out Trash");
// callback();
// },500);
// }
//----Callback hell----
walkDog(()=>{
cleanKitchen(()=>{
takeOutTrash(()=>{
[Link]("You finish all the chores!")
});
});
});
//----Promiese----
function walkDog(){
return new Promise((resolve,reject)=>{
setTimeout(() =>{
const dogwalked = true;
if(dogwalked){
resolve("You walk the dog ");
}
else{

JavaScript Page 127


else{
reject("You didn't walk the dog");
}
},1500);
});
}
function cleanKitchen(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
const clean = true;
if(clean){
resolve("You clean the kitchen ");
}
else{
reject("You didn't clean the kitchen");
}
},2500);
});
}
function takeOutTrash(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
const takeTrash = false;
if(takeTrash){
resolve ou ta e out the trash
}
else{
reject("You didn't take out the trash")
}
},500);
});
}
walkDog().then(value => {[Link](value); return cleanKitchen()})
.then(value => {[Link](value); return takeOutTrash()})
.then(value => {[Link](value); [Link]("You finish
all the chores!")})
.catch(error =>[Link](error));
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Promises</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 128


Async/Await
Monday, July 21, 2025 9:32 PM

async = makes a function return a promise


await = makes a async function wait for a promise

Allows you write asynchronous code in a synchronous manner. Async


doesn't have resolve or reject parameters

Everything after Await is placed in an event queue

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
function walkDog(){
return new Promise((resolve,reject)=>{
setTimeout(() =>{
const dogwalked = true;
if(dogwalked){
resolve("You walk the dog ");
}
else{
reject("You didn't walk the dog");
}
},1500);
});
}
function cleanKitchen(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
const clean = true;
if(clean){
resolve("You clean the kitchen ");
}
else{
reject("You didn't clean the kitchen");
}
},2500);
});
}
function takeOutTrash(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{

const takeTrash = false;

if(takeTrash){
resolve ou ta e out the trash
}
else{
reject("You didn't take out the trash")
}
},500);

JavaScript Page 129


},500);
});
}
async function doChores(){
try{
const walkDogResult = await walkDog();
[Link](walkDogResult);
const cleanKitchenResult = await cleanKitchen();
[Link](cleanKitchenResult);
const takeOutTrashResult = await takeOutTrash();
[Link](takeOutTrashResult);
[Link]("You finished all the chores!!")
}
catch(error){
[Link](error);
}
}
doChores();
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Async/Await</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 130


JSON files
Monday, July 21, 2025 9:32 PM

JSON(JavaScript Object Notation) data-interchange format used


exchanging data between a server and a web application JSON files
{key:value} or [value1,value2,value3]

[Link]() = converts a JS object to a JSON string

[Link]() = converts a JSON string to a JS object

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
const names = ["Tyler","Dean","Akiel","Liam"];
const person =
{"name":"Tyler","age":18,"isEmployed":true,"hobbies":["Coding","Socc
er"]};
const people = [{"name":"Tyler","age":18,"isEmployed":false},
{"name":"Dean","age":18,"isEmployed":false},
{"name":"Akiel","age":20,"isEmployed":true},
{"name":"Liam","age":19,"isEmployed":false}];
const jsonString = [Link](names);
const jsonStringP = [Link](person);
const jsonStringPP = [Link](people);
[Link](jsonString);
[Link](jsonStringP);
[Link](jsonStringPP);
const jsonNames = `["Tyler","Dean","Akiel","Liam"]`;
const jsonPerson =
`{"name":"Tyler","age":18,"isEmployed":true,"hobbies":["Coding","Soc
cer"]}`;
const jsonPeople = `[{"name":"Tyler","age":18,"isEmployed":false},
{"name":"Dean","age":18,"isEmployed":false},
{"name":"Akiel","age":20,"isEmployed":true},
{"name":"Liam","age":19,"isEmployed":false}]`;

const parsedData = [Link](jsonNames);


const parsedDataP = [Link](jsonPerson);
const parsedDataPP = [Link](jsonPeople);
[Link](parsedData);
[Link](parsedDataP);
[Link](parsedDataP);

fetch("[Link]").then(response => [Link]())


.then(value => [Link](value));
fetch("[Link]").then(response => [Link]())
.then(value => {[Link](value)});
fetch("[Link]").then(response => [Link]())
.then(values => [Link](value =>
{[Link]([Link])}));
-------------------------------------------------------------------
JSON 1

JavaScript Page 131


JSON 1
-------------------------------------------------------------------
["Tyler","Dean","Akiel","Liam"]
-------------------------------------------------------------------
JSON 2
-------------------------------------------------------------------
{
"name":"Tyler",
"age":18,
"isEmployed":true,
"hobbies":["Coding","Soccer"]
}
-------------------------------------------------------------------
JSON 3
-------------------------------------------------------------------
[{
"name":"Tyler",
"age":18,
"isEmployed":false
},
{
"name":"Dean",
"age":18,
"isEmployed":false
},
{
"name":"Akiel",
"age":20,
"isEmployed":true
},
{
"name":"Liam",
"age":19,
"isEmployed":false
}]
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>JSON</title>
</head>
<body>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 132


Fetch data from an API
Monday, July 21, 2025 9:32 PM

Function used for making HTTP requests to fetch resources


(JSON style data, images, files)

Simplifies asynchronous data fetching in Javascript and used for


interacting with APIs to retrieve and send data asynchronously over
the web

fetch(url,{options})

fetch(url,{methods: GET})
fetch(url,{methods: POST})
fetch(url,{methods: PUT})
fetch(url,{methods: DELETE})

-------------------------------------------------------------------
JS Page
-------------------------------------------------------------------
// fetch("[Link]
// .then(response => {
// if(![Link]){
// throw new Error("Could not fetch resources");
// }
// [Link]()
// })
// .then(data => [Link]([Link]))
// .catch(error => [Link](error));
async function fetchData(){
try{
const pokemonName =
[Link]("pokemonName").[Link]();
const response = await fetch(`[Link]
${pokemonName}`);
if(![Link]){
throw new Error("Could not fetch resources");
}
const data = await [Link]();
const pokemonSprite = [Link].front_default;
const imgElement = [Link]("pokemonSprite");
[Link] = pokemonSprite;
[Link] = "block";
}
catch(error){
[Link](error);
}
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">

JavaScript Page 133


<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="[Link]">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Fetch API Data</title>
</head>
<body>
<input type="text" id="pokemonName" placeholder="Enter pokemon
name">
<button Pokemon</button>
<img src="" alt="Pokemon Sprite" id="pokemonSprite"
style="display: none;">
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 134


Weather App Project
Monday, July 21, 2025 9:32 PM

JS Page
-------------------------------------------------------------------
const weatherForm = [Link](".weatherForm");
const cityInput = [Link](".cityInput");
const card = [Link](".card");
const apiKey = "f1c457efcfb04e19280a4af64a296fc3";
[Link]("submit", async event =>{
[Link]();
const city = [Link]();
if(city){
try{
const weatherData = await getWeatherData(city);
displayWeatherInfo(weatherData);
}
catch(error){
[Link](error);
displayError(error);
}
}
else{
displayError("Please enter a city");
}
});
async function getWeatherData(city){
const apiUrl = `[Link]
${city}&appid=${apiKey}`;
const response = await fetch(apiUrl);
if(![Link]){
throw new Error("Could not fetch weather data");
}
return await [Link]();
}
function displayWeatherInfo(data){
const {name: city,
main: {temp,humidity},
weather: [{description,id}]} = data;

[Link] = "";
[Link] = "flex";
const cityDisplay = [Link]("h1");
const tempDisplay = [Link]("p");
const humidityDisplay = [Link]("p");
const descDisplay = [Link]("p");
const weatherEmoji = [Link]("p");
[Link] = city;
[Link] = `${(temp - 273.15).toFixed(2)}℃`;
[Link] = `Humidity: ${humidity}%`;
[Link] = description;
[Link] = getWeatherEmoji(id);
[Link]("cityDisplay");

JavaScript Page 135


[Link]("cityDisplay");
[Link]("tempDisplay");
[Link]("humidityDisplay");
[Link]("descDisplay");
[Link]("weatherEmoji");
[Link](cityDisplay);
[Link](tempDisplay);
[Link](humidityDisplay);
[Link](descDisplay);
[Link](weatherEmoji);
}
function getWeatherEmoji(weatherId){
switch(true){
case (weatherId >= 200 && weatherId < 300): return "⛈";
case (weatherId >= 300 && weatherId < 400): return " ";
case (weatherId >= 500 && weatherId < 600): return " ";
case (weatherId >= 600 && weatherId < 700): return "❄";
case (weatherId >= 700 && weatherId < 800): return " ";
case (weatherId === 800): return " ";
case (weatherId > 800 && weatherId < 810): return "☁";
default: return "❓";
}
}
function displayError(message){
const errorDisplay = [Link]("p");
[Link] = message;
[Link]("errorDisplay");
[Link] = "";
[Link] = "flex";
[Link](errorDisplay);
}
-------------------------------------------------------------------
CSS Page
-------------------------------------------------------------------
body{
font-family: Arial, Helvetica, sans-serif;
background-color: hsl(0,0%,95%);
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
}
.weatherForm{
margin: 20px;
}
.cityInput{
padding: 10px;
font-size: 2rem;
font-weight: bold;
border: 2px solid hsla(0, 0%, 0%, 0.315);
border-radius: 10px;
margin: 10px;
width: 20rem;
}

JavaScript Page 136


}
button[type="submit"]{
padding: 10px 20px;
font-weight: bold;
font-size: 2rem;
background-color: lightgreen;
border: none;
color: white;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.15s;
}
button[type="submit"]:hover{
background-color: hsl(120, 73%, 60%);
}
.card{
background: linear-gradient(180deg, hsl(210, 100%, 75%),hsl(40,
100%, 75%));
padding: 50px;
border-radius: 10px;
box-shadow: 2px 2px 5px hsla(0, 0%, 0%, 0.5);
min-width: 20rem;
display: flex;
flex-direction: column;
align-items: center;
}
h1{
margin-top: 0;
margin-bottom: 2rem;
}
p{
font-size: 1.5rem;
margin: 5px 5px;
}
.cityDisplay,
.tempDisplay{
font-size: 3.5rem;
font-weight: bold;
color: hsla(0, 0%, 0%, 0.75);
margin-bottom: 2rem;
}
.humidityDisplay{
font-weight: bold;
margin-bottom: 2rem;
}
.descDisplay{
font-style: italic;
font-weight: bold;
font-size: 2rem;
}
.weatherEmoji{
margin: 0;
font-size: 7.5rem;
}
.errorDisplay{

JavaScript Page 137


.errorDisplay{
font-size: 2.5rem;
font-weight: bold;
color: hsla(0, 0%, 0%, 0.75);
}
-------------------------------------------------------------------
HTML Page
-------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="[Link]">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
1.0">
<title>Weather App</title>
</head>
<body>
<form class="weatherForm">
<input type="text" class="cityInput" placeholder="Enter city">
<button type="submit">Get Weather</button>
</form>
<div class="card" style="display: none;"></div>
<script src="[Link]"></script>
</body>
</html>
-------------------------------------------------------------------

JavaScript Page 138

You might also like