Java Script
Java Script
JavaScript is versatile and can be used on both the client-side and server-
side of web development.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Console Log</title>
</head>
<body>
<h1>Check the console for JavaScript output!</h1>
<script src="[Link]"></script>
</body>
</html>
Handson VS Code Setup
[Link]
Strings: Text data, enclosed in single or double quotes. let greeting = "Hello, world!";
Arrays: Used to store multiple values in a single variable. let fruits = ["Apple", "Banana", "Orange"];
Objects: Used to store key-value pairs let person = { name: "John", age: 30, isStudent: false };
let sum = 5 + 3; // 8
Arithmetic Operators: +, -, *, /, % (modulus), ** (exponentiation)
let product = 5 * 2; // 10
let x = 10;
#2 JavaScript Basics Assignment Operators: =, +=, -=, *=, /=
x += 5; // x is now 15
#3 Operators
Logical Operators: && (AND), || (OR), ! (NOT) let result = (5 > 3 && 2 < 4); // true
prompt(): Displays a dialog box to take user input. let userName = prompt("What is your name?");
// Perform calculations
Takes two numbers from the user using prompt. let sum = num1 + num2;
let difference = num1 - num2;
#1 Simple Calculator Create a simple calculator that: Calculates the sum, difference, product, and quotient. Code let product = num1 * num2;
let quotient = num1 / num2;
Displays the results using alert.
// Display the results using alert
alert("Sum: " + sum);
alert("Difference: " + difference);
alert("Product: " + product);
alert("Quotient: " + quotient);
Exercise
switch (day) {
case "A":
[Link]("Monday");
break;
case "B":
[Link]("Tuesday");
break;
default:
[Link]("Unknown day");
}
let i = 0;
while (i < 5)
{
while loop: Runs a block of code as long as the condition is true.
[Link](i);
#3 Control Structures & Loops #2 Loops i++;
}
let i = 0;
do
{
do...while loop: Similar to while, but guarantees the block of code will run
[Link](i);
at least once.
i++;
}
Exercise
Write a program to print the first 10 Fibonacci for (let i = 3; i <= 10; i++)
#2 Fibonacci Sequence
numbers using a for loop. {
let nextNum = num1 + num2;
[Link](nextNum);
function greet()
{
Function Declaration: A named function that
[Link]("Hello, world!");
can be called anywhere in the code, even
}
before its definition, due to hoisting
greet(); // Call the function
#1 Function Declarations and Expressions
function add(a, b)
{
return a + b;
Parameters: Input values passed into the function.
}
function square(num) {
return num * num;
Return Values: The result that a function returns
}
after execution.
[Link](square(4)); // Output: 16
function displayGlobalVar()
Global Scope: Variables declared outside of any function are {
global and can be accessed anywhere in the script. [Link](globalVar); // Can access globalVar
}
#4 Functions & Scope
displayGlobalVar(); // Output: "I am global!"
function displayLocalVar()
{
let localVar = "I am local!";
Local Scope: Variables declared inside a function are local [Link](localVar); // Can access localVar
and only accessible within that function. }
// Area of a rectangle
function areaOfRectangle(length, width)
{
return length * width;
}
// Area of a circle
function areaOfCircle(radius)
{
return [Link] * radius * radius;
Create functions to calculate the area of a }
Area Calculators
rectangle, a circle, and a triangle.
// Area of a triangle
function areaOfTriangle(base, height)
{
return (base * height) / 2;
}
function largerNumber(a, b)
{
return a > b ? a : b;
Write a function that takes two numbers as }
Find the Larger of Two Numbers
arguments and returns the larger one.
// Test the function
[Link](largerNumber(10, 5)); // Output: 10
[Link](largerNumber(7, 7)); // Output: 7
An array is a special variable that can hold multiple values at once. Arrays let fruits = ["Apple", "Banana", "Mango"];
#1 Arrays
are zero-indexed, meaning the first element has an index of 0 [Link](fruits[0]); // Output: "Apple"
[Link]();
pop(): Removes the last element from an array.
[Link](fruits); // ["Apple", "Banana"]
[Link]();
shift(): Removes the first element from an array.
[Link](fruits); // ["Banana"]
Java Script splice(start, deleteCount, ...items): let fruits = ["Apple", "Banana", "Mango"];
Adds/removes items to/from an array. Can add
new elements, remove existing ones, or do // Replacing "Banana" with "Pineapple" at index 1
both. [Link](1, 1, "Pineapple");
[Link](fruits); // Output: ["Apple", "Pineapple", "Mango"]
Replace
// Replacing "Mango" with two elements: "Grapes" and "Peach" at index 2
[Link](2, 1, "Grapes", "Peach");
[Link](fruits); // Output: ["Apple", "Pineapple", "Grapes", "Peach"]
#2 Common Array Methods
Remove // Removing all elements starting from index 2 (removes "Mango", "Orange", "Grapes")
[Link](2);
[Link](fruits); // Output: ["Apple", "Banana"]
Slicing From a Start Index to the End // Slice from index 2 to the end of the array
let portion = [Link](2);
[Link](portion); // Output: ["Mango", "Orange", "Grapes"]
Remove the first movie using shift(). // Step 3: Remove the first movie using shift
[Link]();
[Link](movies); // ["The Matrix", "Interstellar", "Fight Club", "The Dark Knight", "The Lord of the Rings"]
let student =
{
An object in JavaScript is a collection of key-
name: "John",
#1 Creating Objects (Key-Value Pairs) value pairs. Keys are also known as properties,
age: 20,
and each key has an associated value.
grade: "A"
};
[Link]([Link]); // "John"
Dot notation
[Link] = 21; // Modify the age
let car = {
brand: "Tesla",
model: "Model S",
features:
{
Nested Objects: An object can contain other
autopilot: true,
objects as values. batteryLife: "500 miles"
}
};
[Link]([Link]); // true
#3 Nested Objects and Arrays of Objects
let books = [
{ title: "1984", author: "George Orwell", year: 1949 },
Array of Objects: An array can store multiple { title: "The Catcher in the Rye", author: "J.D. Salinger", year: 1951 }
objects. ];
Exercise
// Step 1: Create the array of books
let books = [
{ title: "The Da Vinci Code", author: "Dan Brown", year: 2003 },
{ title: "Harry Potter and the Goblet of Fire", author: "J.K. Rowling", year: 2000 },
{ title: "The Road", author: "Cormac McCarthy", year: 2006 }
];
Create an array of objects representing a list
of books, each with title, author, and year. // Step 2: Write a function to find books published after 2000
Array of Book Objects code function findBooksAfter2000(books) {
Write a function to find all books published return [Link](function(book) {
after the year 2000. return [Link] > 2000;
});
}
<!DOCTYPE html>
<html lang="en">
Document: Represents the entire HTML document. <head>
The DOM is a programming interface for web <meta charset="UTF-8">
Understanding the DOM (Document Object documents. It represents the page so <meta name="viewport" content="width=device-width, initial-scale=1.0">
#1 Object: Each HTML element (e.g., <div>, <p>) is represented as an object.
Model) programs can change the document structure, <title>DOM Manipulation</title>
style, and content. <style>
Model: A tree-like structure where each element is a node. #myElement {
color: red;
font-size: 20px;
getElementById(): Selects an element by its id. let element = [Link]("myElement"); }
.newClass {
To manipulate the DOM, we first need to color: green;
querySelector(): Selects the first element let element = [Link](".myClass"); // For class
#2 Selecting Elements select the elements we want to work with. }
that matches a CSS selector. let element = [Link]("#myId"); // For ID
Common methods include: </style>
</head>
<body>
querySelectorAll(): Selects all elements that
let elements = [Link]("p");
match a CSS selector.
<h1 id="header">DOM Manipulation Demo</h1>
Changing Text Content: We can change the <!-- Existing Elements -->
content of an HTML element using textContent [Link]("myElement").textContent = "Hello, World!"; <div id="myElement">This is the original text!</div>
or innerHTML.
#3 Changing Content and Styles <button id="changeTextButton">Change Text</button>
Changing Styles: We can change the CSS <button id="addElementButton">Add New Element</button>
styles of an element by modifying its style [Link]("myElement").[Link] = "blue"; <button id="removeElementButton">Remove Element</button>
property.
<div id="parentElement">
<p id="childElement">I am a removable child element.</p>
Creating Elements: Use </div>
let newElement = [Link]("p");
[Link]() to create a new [Link] = "This is a new paragraph."; code
HTML element. <script>
// Selecting an element by its ID and changing its content
Appending Elements: Use appendChild() to [Link]("changeTextButton").addEventListener("click", function() {
#4 Adding and Removing Elements Dynamically [Link](newElement); let element = [Link]("myElement");
add a new element to the DOM.
[Link] = "Hello, World!";
[Link] = "blue"; // Changing the style
let parent = [Link]("parentElement"); });
Removing Elements: Use removeChild() to
let child = [Link]("childElement");
remove an element from the DOM. [Link](child); // Creating a new element and appending it to the DOM
[Link]("addElementButton").addEventListener("click", function() {
let newElement = [Link]("p");
[Link] = "This is a dynamically added paragraph!";
<!-- Step 1: Create an HTML form --> [Link] = "newClass"; // Adding a class to style the new element
<!DOCTYPE html> [Link](newElement); // Appending the new element to the body
<html lang="en"> });
#7 DOM Manipulation <head>
<meta charset="UTF-8"> // Removing an existing element from the DOM
<meta name="viewport" content="width=device-width, initial-scale=1.0"> [Link]("removeElementButton").addEventListener("click", function() {
<title>Form Example</title> let parent = [Link]("parentElement");
</head> let child = [Link]("childElement");
<body> if (child) {
[Link](child); // Removing the child element
<h1>Click the Button</h1> } else {
<form> alert("Child element is already removed!");
Create a simple HTML form with a button. <button type="button" id="myButton">Click Me!</button> }
HTML Form with Button and Message </form> });
code
Use JavaScript to display a message when the </script>
button is clicked. <p id="message"></p>
</body>
<script> </html>
// Step 2: Use JavaScript to display a message when the button is clicked
[Link]("myButton").addEventListener("click", function()
{
[Link]("message").textContent = "Button was clicked!";
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic List</title>
</head>
<body>
<h1>Favorite Fruits</h1>
<ul id="fruitList"></ul>
Create a list of items dynamically from an
array. <script>
Create a List Dynamically from an Array code // Step 1: Create an array of fruits
let fruits = ["Apple", "Banana", "Mango", "Orange", "Pineapple"];
Exercise Display the list in a <ul> using JavaScript.
// Step 2: Dynamically create a list and display it in the <ul>
let ul = [Link]("fruitList");
[Link](function(fruit) {
let li = [Link]("li");
[Link] = fruit;
[Link](li);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Enter a task">
<button id="addTaskButton">Add Task</button>
<ul id="taskList"></ul>
<script>
Create a to-do list where users can add tasks. // Step 1: Add a task when the button is clicked
[Link]("addTaskButton").addEventListener("click", function() {
Dynamic To-Do List code let taskInput = [Link]("taskInput").value;
Users can remove tasks by clicking on them if ([Link]() !== "") {
using removeChild(). let li = [Link]("li");
[Link] = taskInput;
[Link]("taskList").appendChild(li);
[Link]("taskInput").value = ""; // Clear the input field
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Events and Form Validation</title>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
Exercise <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<h1>Register Form</h1>
<form id="registerForm">
<label for="email">Email:</label>
<input type="email" id="email" required><br><br>
<button type="submit">Register</button>
Create a form that validates user input (e.g.,
</form>
Form Validation email format, minimum password length)
before submission.
<script>
// Add form validation on submit
[Link]("registerForm").addEventListener("submit", function(event) {
let email = [Link]("email").value;
let password = [Link]("password").value;
if () {
alert("Please enter a valid email address.");
[Link](); // Prevent form submission
} else if ([Link] < 6) {
alert("Password must be at least 6 characters long.");
[Link](); // Prevent form submission
}
});
</script>
</body>
</html>