0% found this document useful (0 votes)
6 views1 page

Java Script

JavaScript is a high-level, interpreted programming language essential for web development, enabling interactivity on both client and server sides. It includes various frameworks and libraries like React, Vue.js, and Node.js, which facilitate building dynamic applications. The document also covers fundamental JavaScript concepts, including variables, data types, operators, control structures, functions, and arrays.

Uploaded by

mfc17753
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)
6 views1 page

Java Script

JavaScript is a high-level, interpreted programming language essential for web development, enabling interactivity on both client and server sides. It includes various frameworks and libraries like React, Vue.js, and Node.js, which facilitate building dynamic applications. The document also covers fundamental JavaScript concepts, including variables, data types, operators, control structures, functions, and arrays.

Uploaded by

mfc17753
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 (JS) is a high-level, interpreted programming language primarily

used to make web pages interactive.

It is one of the core technologies of the web, alongside HTML (structure)


and CSS (style).

JavaScript is versatile and can be used on both the client-side and server-
side of web development.

Runs directly in the browser. It enables dynamic


content, such as animations, form validations,
interactive maps, and other elements that make
web pages more engaging.
Client-side JavaScript
Client-side JavaScript is executed after the
HTML and CSS have been loaded and helps in
creating a richer user experience.

Runs on the server, most commonly using


platforms like [Link].

It handles tasks like interacting with databases,


Server-side JavaScript
file systems, and APIs.

Server-side JavaScript helps create dynamic


web content, such as generating HTML based
on user data or handling backend services.

A JavaScript library developed by Facebook,


used for building interactive UIs. React focuses
React
on component-based architecture and is highly
efficient in rendering dynamic content.

A progressive framework for building user


Front end Frameworks [Link] interfaces, known for its simplicity and ease of
integration with other projects.

A TypeScript-based front-end framework


Angular developed by Google, used for building
complex, large-scale web applications.

A JavaScript runtime built on Chrome's V8


engine. It allows you to run JavaScript on the
[Link]
server side and is widely used for building
scalable, event-driven applications.
Back end Frameworks
#1 Introduction to JavaScript
A minimal, fast framework for building web
[Link]
servers and APIs on top of [Link].

A fast, small, and feature-rich JavaScript library


that simplifies tasks like HTML DOM
manipulation, event handling, and AJAX
requests.
jQuery
Tools & Libraries
While it's less popular today with modern
frameworks, it remains foundational.
Libraries
A powerful library for data visualization,
allowing developers to bind data to a
[Link]
Document Object Model (DOM) and apply
data-driven transformations.

A delightful JavaScript testing framework with


Jest a focus on simplicity and support for large web
applications.
Testing Frameworks
A feature-rich JavaScript test framework that
Mocha
runs on [Link], useful for asynchronous testing.

A static module bundler for modern JavaScript


Webpack applications, which compiles multiple modules
into a single file or smaller bundles.
Build Tools
A simpler, zero-config bundler that allows
Parcel developers to package their JavaScript projects
with minimal setup.

[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]

// This will print "Hello, JavaScript!" in the browser console


[Link]("Hello, JavaScript!");

let: Used to declare block-scoped variables


that can be reassigned.

const: Used to declare block-scoped variables


that cannot be reassigned.

var: A function-scoped variable (older,


#1 Variables: let, const, and var
generally avoided in modern JavaScript).

let age = 25; // Can be reassigned

const name = "John"; // Cannot be reassigned

var isStudent = true; // Function-scoped, rarely used today

let num = 10;


Numbers: Integers, floating-point numbers.
let price = 19.99;

Strings: Text data, enclosed in single or double quotes. let greeting = "Hello, world!";

#2 Data Types Booleans: Represents true or false. let isAdult = true;

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

let isEqual = (5 == "5"); // true


Comparison Operators: ==, === (strict equality), !=, !==, <, >, <=, >=
let isStrictEqual = (5 === "5"); // false

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?");

#4 Basic Input/Output: prompt and alert

alert(): Displays a pop-up alert to the user. alert("Hello, " + userName);

// Get two numbers from the user


let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second
number:"));

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

// Store user details


let userName = prompt("What is your name?");
let userAge = parseInt(prompt("How old are you?"));
let isStudent = prompt("Are you a student? (yes/no)").toLowerCase() === "yes";
Store the user’s name, age, and student status
#2 Store and Print User Details
in variables and print them to the console.
Code
// Print user details to the console
[Link]("Name:", userName);
[Link]("Age:", userAge);
[Link]("Student:", isStudent);

if (age >= 18)


{
if statement: Executes a block of code if a condition is true.
[Link]("You are an adult.");
}

if (age >= 18)


{
[Link]("You are an adult.");
else if statement: Adds another condition to check if the }
initial if condition is false. else if (age >= 13)
{
[Link]("You are a teenager.");
}

let age = parseInt(prompt("What is your


if (age >= 18) Age?"));
{ let height = parseFloat(prompt("enter ur
[Link]("You are an adult."); height:"));
else statement: Executes if none of the previous conditions }
#1 Conditional Statements
are true. else let age2 = prompt("What is your Age?");
{ let height2 = prompt("enter ur height:");
[Link]("You are not an adult.");
} if (age == 18) {
[Link]("You are exactly 18");
} else if (age >= 18) {
code [Link]("You are a adult.");
switch (day) } else if (age >= 13) {
{ [Link]("You are a Teenager.");
case 1: } else {
[Link]("Monday"); [Link]("You are not an adult.");
break; }
case 2: [Link](age);
[Link]("Tuesday"); [Link](height);
break; [Link](age + height);
default: [Link](age2 + height2);
[Link]("Unknown day");
}

switch statement: Used for multiple choices based on the


value of an expression.
let day = prompt("Enter Char?");

switch (day) {
case "A":
[Link]("Monday");
break;
case "B":
[Link]("Tuesday");
break;
default:
[Link]("Unknown day");
}

for (let i = 0; i < 5; i++)


{
for loop: Runs a block of code for a specific number of iterations.
[Link](i);
}

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++;
}

while (i < 5);

for (let i = 1; i <= 3; i++)


{
if (i % 2 === 0)
{
[Link](i + " is even");
You can nest loops inside conditional
#3 Nesting Loops and Conditions }
statements or other loops for complex logic.
else
{
[Link](i + " is odd");
}
}

// Get the user's age


let age = parseInt(prompt("Enter your age:"));

// Determine if the user is a minor, adult, or senior citizen


if (age < 18)
{
[Link]("You are a minor.");
Create a program that takes a user’s age and
}
#1 Age Classification prints whether they are a minor, an adult, or a
else if (age >= 18 && age <= 60)
senior citizen.
{
[Link]("You are an adult.");
}
else
{
[Link]("You are a senior citizen.");
}

Exercise

// Initialize the first two Fibonacci numbers


let num1 = 0, num2 = 1;

// Print the first 10 Fibonacci numbers


[Link](num1); // Print 0
[Link](num2); // Print 1

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

// Update the values for the next iteration


num1 = num2;
num2 = 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 Expression: A function assigned to a


variable. It can only be called after the
expression is defined

function add(a, b)
{
return a + b;
Parameters: Input values passed into the function.
}

[Link](add(3, 5)); // Output: 8


#2 Parameters and Return Values

function square(num) {
return num * num;
Return Values: The result that a function returns
}
after execution.
[Link](square(4)); // Output: 16

Arrow functions provide a shorter syntax for


writing functions. const add = (a, b) => a + b;
#3 Arrow Functions
They are especially useful for concise, one- [Link](add(2, 3)); // Output: 5
liner functions.

let globalVar = "I am global!";

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

#4 Understanding Local vs. Global Scope

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

displayLocalVar(); // Output: "I am local!"


// [Link](localVar); // Error: localVar is not defined

// 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;
}

// Test the functions


Exercise [Link]("Rectangle Area: " + areaOfRectangle(5, 3)); // Rectangle Area: 15
[Link]("Circle Area: " + areaOfCircle(4)); // Circle Area: 50.26548245743669
[Link]("Triangle Area: " + areaOfTriangle(5, 4)); // Triangle Area: 10

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"

let fruits = ["Apple", "Banana"];


push(): Adds a new element to the end of an array. [Link]("Mango");
[Link](fruits); // ["Apple", "Banana", "Mango"]

[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"]

unshift(): Adds a new element to the beginning [Link]("Orange");


of an array. [Link](fruits); // ["Orange", "Banana"]

let fruits = ["Apple", "Banana", "Mango", "Orange"];

// Removing 1 element from index 1 (removes "Banana")


[Link](1, 1);
[Link](fruits); // Output: ["Apple", "Mango", "Orange"]
Remove
// Removing 2 elements starting from index 1 (removes "Mango" and "Orange")
[Link](1, 2);
[Link](fruits); // Output: ["Apple"]

let fruits = ["Apple", "Banana", "Mango"];

// Adding 1 element at index 1 ("Orange" will be added after "Apple")


[Link](1, 0, "Orange");
[Link](fruits); // Output: ["Apple", "Orange", "Banana", "Mango"]
Add
// Adding 2 elements at index 2 ("Grapes", "Peach" will be added after "Banana")
[Link](2, 0, "Grapes", "Peach");
[Link](fruits); // Output: ["Apple", "Orange", "Grapes", "Peach", "Banana", "Mango"]

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

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];

Remove // Removing all elements starting from index 2 (removes "Mango", "Orange", "Grapes")
[Link](2);
[Link](fruits); // Output: ["Apple", "Banana"]

let fruits = ["Apple", "Banana", "Mango"];

// Removing 1 element at index 1 ("Banana") and adding "Orange" and "Peach"


[Link](1, 1, "Orange", "Peach");
Remove + Add [Link](fruits); // Output: ["Apple", "Orange", "Peach", "Mango"]

// Removing 2 elements at index 2 ("Peach", "Mango") and adding "Grapes"


[Link](2, 2, "Grapes");
[Link](fruits); // Output: ["Apple", "Orange", "Grapes"]

let fruits = ["Apple", "Banana", "Mango", "Orange"];

// Slice from index 1 to index 2 (not inclusive of index 2)


let citrus = [Link](1, 2);
[Link](citrus); // Output: ["Banana"]

// The original array is not modified


[Link](fruits); // Output: ["Apple", "Banana", "Mango", "Orange"]
#5 Arrays & Array Methods

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];


slice(start, end): Returns a new array from the
original array, extracting elements from start Extracting portion of array // Slice from index 1 to index 4 (not inclusive of index 4)
index to end (not inclusive). let portion = [Link](1, 4);
[Link](portion); // Output: ["Banana", "Mango", "Orange"]

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];

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"]

Does not modify the original array.

Returns a new array with the extracted


slice()
elements.

Parameters: (start, end) (end is not included).


Key Differences Between slice() and splice()
Modifies the original array by adding/removing elements.

splice() Returns the removed elements.

Parameters: (start, deleteCount, ...items).

let numbers = [1, 2, 3];


[Link](function(number)
forEach(): Executes a function for each
{
element in the array.
[Link](number * 2); // Prints 2, 4, 6
});

let numbers = [1, 2, 3];


let doubled = [Link](function(number)
map(): Creates a new array by applying a {
function to each element in the array. return number * 2;
});
[Link](doubled); // [2, 4, 6]

#3 Higher-Order Array Methods


let numbers = [1, 2, 3, 4, 5];
let evens = [Link](function(number)
filter(): Creates a new array with elements {
that pass a given condition. return number % 2 === 0;
});
[Link](evens); // [2, 4]

let numbers = [1, 2, 3, 4];


let sum = [Link](function(accumulator, current)
reduce(): Reduces an array to a single value
{
by executing a reducer function on each
return accumulator + current;
element.
}, 0);
[Link](sum); // 10

// Step 1: Create an array of favorite movies


let movies = ["Inception", "The Matrix", "Interstellar", "Fight Club", "The Dark Knight"];
Create an array of five favorite movies.
// Step 2: Add a new movie using push
[Link]("The Lord of the Rings");
Manipulating Movies Array Add a new movie using push(). code [Link](movies); // ["Inception", "The Matrix", "Interstellar", "Fight Club", "The Dark Knight", "The Lord of the Rings"]

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"]

// Step 1: Create an array of numbers


let numbers = [1, 2, 3, 4, 5];

Create an array of numbers. // Step 2: Use map to double each value


Use map() to Double Each Value code let doubledNumbers = [Link](function(number)
Exercise Use map() to double each value in the array. {
return number * 2;
});
[Link](doubledNumbers); // [2, 4, 6, 8, 10]

// Step 1: Create an array of numbers


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

// Step 2: Use reduce to sum the numbers


let totalSum = [Link](function(accumulator, current)
{
Use reduce() to sum the numbers in an array. return accumulator + current;
Use reduce() and filter() }, 0);
code
Use filter() to return only even numbers from [Link]("Total Sum:", totalSum); // Output: 55
the array.
// Step 3: Use filter to return only even numbers
let evenNumbers = [Link](function(number)
{
return number % 2 === 0;
});
[Link]("Even Numbers:", evenNumbers); // Output: [2, 4, 6, 8, 10]

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

#2 Accessing and Modifying Object Properties

Bracket notation (useful when the key is [Link](student["grade"]); // "A"


stored as a variable): student["grade"] = "B"; // Modify the grade

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

#6 Objects & JSON [Link](books[0].title); // "1984"

let studentJSON = '{"name": "John", "age": 20, "grade": "A"}';

JSON is a lightweight format used to represent


Introduction to JSON (JavaScript Object data. It looks similar to JavaScript objects, but [Link](): Converts a JavaScript object let jsonString = [Link](student);
#4
Notation) the keys must be strings wrapped in double into a JSON string. [Link](jsonString); // '{"name":"John","age":20,"grade":"A"}'
quotes.

[Link](): Converts a JSON string into a let jsonObject = [Link](jsonString);


JavaScript object. [Link]([Link]); // "John"

// Step 1: Create the student object


let student = {
name: "Alice",
age: 22,
subjects: ["Math", "Physics", "Computer Science"]
};
Create an object representing a student with
properties: name, age, and subjects (an array). // Step 2: Write a function to print student details
Student Object with Array of Subjects code function printStudentDetails(student) {
[Link]("Name:", [Link]);
Write a function to print the student’s details. [Link]("Age:", [Link]);
[Link]("Subjects:", [Link](", "));
}

// Test the function


printStudentDetails(student);

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;
});
}

// Test the function


let recentBooks = findBooksAfter2000(books);
[Link](recentBooks);

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

// Step 2: Remove the task when clicked


[Link]("click", function() {
[Link](li);
});

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

<h1>Event Handling and Form Validation</h1>

<!-- Button for Event Listener Example -->


<button id="myButton">Click Me!</button>
<p id="buttonStatus"></p>
click: Fires when an element is clicked.
Events are actions or occurrences that happen
in the browser, such as a user clicking a <!-- Form for Validation -->
#1 Introduction to Events input: Fires when the value of an <input> or <textarea> changes. <form id="registerForm" onsubmit="return validateForm()">
button, typing into a form field, or submitting
a form. Common types of events include <label for="email">Email:</label>
submit: Fires when a form is submitted. <input type="email" id="email" required><br><br>

<label for="password">Password (min 6 characters):</label>


let button = [Link]("myButton"); <input type="password" id="password" required><br><br>
To respond to events, we use event listeners. [Link]("click", function()
#2 Adding Event Listeners The addEventListener() method attaches a { <button type="submit">Submit</button>
function to an event on a specified element. [Link]("Button clicked!"); </form>
});
<script>
// Adding an Event Listener to the Button
let button = [Link]("myButton");
function validateForm() { code [Link]("click", function() {
let email = [Link]("email").value; [Link]("Button clicked!");
let password = [Link]("password").value; [Link]("buttonStatus").textContent = "Button was clicked!";
});
if (![Link]("@")) {
Form validation ensures that user input alert("Please enter a valid email address."); // Form Validation
follows specific rules (e.g., valid email format, return false; function validateForm() {
minimum password length). } let email = [Link]("email").value;
#3 Form Validation and Handling User Inputs
let password = [Link]("password").value;
This can be done using JavaScript before the if ([Link] < 6) {
form is submitted. alert("Password must be at least 6 characters long."); // Check if the email contains "@"
return false; if (![Link]("@")) {
} alert("Please enter a valid email address.");
return false; // Prevent form submission
return true; }
}
// Check if the password is at least 6 characters long
#8 Events and Event Listeners
if ([Link] < 6) {
<!DOCTYPE html> alert("Password must be at least 6 characters long.");
<html lang="en"> return false; // Prevent form submission
<head> }
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> // If all validations pass
<title>Button Event Listener</title> return true;
</head> }
<body> </script>

<h1>Change the Text</h1> </body>


<p id="text">This is the original text.</p> </html>
Add an event listener to a button that changes
Button with Event Listener <button id="changeTextButton">Click me!</button>
the text of a paragraph when clicked.
<script>
// Add event listener to the button
[Link]("changeTextButton").addEventListener("click", function()
{
[Link]("text").textContent = "The text has been changed!";
});
</script>

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

<label for="password">Password (min 6 characters):</label>


<input type="password" id="password" 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 (![Link]("@")) {
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>

You might also like