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

Javascript Class

The document provides a comprehensive guide on JavaScript concepts including array methods, objects, functions, event handling, and DOM manipulation. It also covers practical examples such as a dynamic to-do list, timers, animations, and web storage techniques like local and session storage. Each section includes code snippets and explanations to facilitate understanding of the topics discussed.

Uploaded by

I No
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

Javascript Class

The document provides a comprehensive guide on JavaScript concepts including array methods, objects, functions, event handling, and DOM manipulation. It also covers practical examples such as a dynamic to-do list, timers, animations, and web storage techniques like local and session storage. Each section includes code snippets and explanations to facilitate understanding of the topics discussed.

Uploaded by

I No
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Adding items

js
CopyEdit
[Link]("yellow"); // add to end
[Link]("pink"); // add to start

Removing items
js
CopyEdit
[Link](); // remove last
[Link](); // remove first

💥 ✅ 4️⃣Advanced Array Methods (map, filter, reduce)


map()
js
CopyEdit
let prices = [100, 200, 300];
let discounted = [Link](price => price - 20);
[Link](discounted); // [80, 180, 280]

filter()
js
CopyEdit
let numbers = [12, 45, 67, 23, 8];
let large = [Link](num => num > 30);
[Link](large); // [45, 67]

reduce()
js
CopyEdit
let nums = [10, 20, 30];
let total = [Link]((sum, num) => sum + num, 0);
[Link](total); // 60

💥 ✅ 5️⃣Objects & Nested Objects


Basic object
js
CopyEdit
let student = {
name: "Alex",
age: 20,
course: "Web Development"
};
[Link]([Link]);

Add new property


js
CopyEdit
[Link] = "A";
[Link](student);

Nested object
js
CopyEdit
let user = {
username: "coder",
profile: {
city: "Chennai",
age: 25
}
};
[Link]([Link]); // Chennai

💥 ✅ 6️⃣Functions inside objects (Methods)


js
CopyEdit
let car = {
brand: "Tesla",
start: function() {
[Link]("Car started!");
}
};

[Link]();

💥 ✅ 7️⃣Events & DOM manipulation (Advanced)


Change styles
js
CopyEdit
function makeRed() {
[Link] = "red";
}
html
CopyEdit
<button onclick="makeRed()">Make Red</button>

Change multiple elements


js
CopyEdit
function changeAll() {
let items = [Link]("p");
[Link](function(p) {
[Link] = "blue";
});
}
html
CopyEdit
<button onclick="changeAll()">Change Paragraphs</button>

💥 ✅ 8️⃣Mini Project: Dynamic To-Do List


 Add task
 Display list
 Delete task

HTML
html
CopyEdit
<input type="text" id="task" placeholder="New task">
<button onclick="addTask()">Add</button>
<ul id="taskList"></ul>

JS
js
CopyEdit
let tasks = [];

function addTask() {
let t = [Link]("task").value;
[Link](t);
display();
[Link]("task").value = "";
}

function display() {
let list = [Link]("taskList");
[Link] = "";
[Link]((item, index) => {
[Link] += `<li>${item} <button onclick="remove($
{index})">Remove</button></li>`;
});
}

function remove(index) {
[Link](index, 1);
display();
}

Syntax of if statement
js
CopyEdit
if (condition) {
// code to run if condition is true
}

Syntax of if-else
js
CopyEdit
if (condition) {
// true block
} else {
// false block
}

Syntax of if-else if-else


js
CopyEdit
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// final block
}

Example: Check voting eligibility


js
CopyEdit
let age = 17;

if (age >= 18) {


[Link]("You can vote!");
} else {
[Link]("Sorry, you are too young to vote.");
}

Example: Check grade category


js
CopyEdit
let mark = 75;

if (mark >= 90) {


[Link]("Grade: A+");
} else if (mark >= 80) {
[Link]("Grade: A");
} else if (mark >= 70) {
[Link]("Grade: B");
} else {
[Link]("Grade: C");
}

Explanation (Detailed)

 Conditions are checked from top to bottom.


 Once a condition is true, remaining blocks are skipped.
 Else block runs only when all above fail.

Diagram (Text Diagram)


mathematica
CopyEdit
Start
|
Check Condition 1
|--- True --> Run Block 1
|
Check Condition 2
|--- True --> Run Block 2
|
Else
--> Run Default Block

Class Task
Write a function to check if a number is positive, negative, or zero.

✅ 5️⃣Array methods (Huge Explanation)


push()

Adds to end.

js
CopyEdit
[Link]("Purple");

pop()

Removes last.

js
CopyEdit
[Link]();

shift()

Removes first.

js
CopyEdit
[Link]();

unshift()

Adds to start.

js
CopyEdit
[Link]("Orange");

forEach()
js
CopyEdit
[Link](function(item, index) {
[Link](index + ": " + item);
});

filter()
js
CopyEdit
let scores = [45, 67, 89, 12];
let passed = [Link](score => score >= 50);
[Link](passed); // [67, 89]

reduce()
js
CopyEdit
let amounts = [100, 200, 300];
let total = [Link]((sum, value) => sum + value, 0);
[Link](total); // 600

✅ 6️⃣Objects (Very Detailed)


What is an object?

A structure for storing related data and functions.

Example
js
CopyEdit
let person = {
name: "John",
age: 25,
city: "Chennai"
};
[Link]([Link]);

Adding property
js
CopyEdit
[Link] = "India";
Nested object
js
CopyEdit
let user = {
id: 1,
profile: {
username: "alex",
email: "alex@[Link]"
}
};
[Link]([Link]);

Method inside object


js
CopyEdit
let dog = {
breed: "Labrador",
bark: function() {
[Link]("Woof!");
}
};
[Link]();

✅ 7️⃣DOM Manipulation (Big Section)


Changing text
js
CopyEdit
[Link]("demo").innerHTML = "Changed!";

Changing style
js
CopyEdit
[Link]("box").[Link] = "blue";

Creating element
js
CopyEdit
let para = [Link]("p");
[Link] = "Hello!";
[Link](para);
Removing element
js
CopyEdit
let el = [Link]("demo");
[Link]();

✅ 8️⃣Event Handling (Expanded)


onclick
html
CopyEdit
<button onclick="sayHi()">Click me</button>
js
CopyEdit
function sayHi() {
alert("Hello!");
}

mouseover
html
CopyEdit
<div onmouseover="hovered()">Hover here</div>
js
CopyEdit
function hovered() {
[Link]("Mouse is over the element!");
}

keypress
js
CopyEdit
[Link]("keypress", function(event) {
[Link]("Key pressed: " + [Link]);
});

✅ 9️⃣Mini Project
HTML
html
CopyEdit
<input id="num1">
<input id="num2">
<button onclick="add()">Add</button>
<p id="result"></p>

JS
js
CopyEdit
function add() {
let a = parseFloat([Link]("num1").value);
let b = parseFloat([Link]("num2").value);
[Link]("result").innerText = "Result: " + (a + b);
}

✅ 🔥 Extra Project — Dynamic List


HTML
html
CopyEdit
<input type="text" id="itemInput">
<button onclick="addItem()">Add Item</button>
<ul id="itemList"></ul>

JS
js
CopyEdit
function addItem() {
let item = [Link]("itemInput").value;
let li = [Link]("li");
[Link] = item;
[Link]("itemList").appendChild(li);
}

✅ 1️⃣ Introduction to Timers


Why do we need timers?

Timers allow us to:

 Delay execution of code


 Repeat certain actions periodically
 Create animations, clocks, sliders, countdowns
✅ 2️⃣setTimeout()
Syntax
js
CopyEdit
setTimeout(function, milliseconds)

 Executes the function once after the specified delay.

Example 1: Simple delay


js
CopyEdit
[Link]("Message 1");
setTimeout(function() {
[Link]("Message 2 (after 2 seconds)");
}, 2000);
[Link]("Message 3");
Explanation

 Message 1 prints immediately


 Message 3 prints immediately
 Message 2 prints after 2 seconds

Example 2: Change text after delay


html
CopyEdit
<p id="demo">Hello</p>
<button onclick="changeText()">Change After Delay</button>

<script>
function changeText() {
setTimeout(function() {
[Link]("demo").innerHTML = "Text changed!";
}, 1000);
}
</script>

✅ 3️⃣setInterval()
Syntax
js
CopyEdit
setInterval(function, milliseconds)

 Repeats execution forever at specified intervals until stopped.

Example: Counter
html
CopyEdit
<p id="count">0</p>
<button onclick="startCount()">Start Counting</button>

<script>
let counter = 0;
let intervalId;

function startCount() {
intervalId = setInterval(function() {
counter++;
[Link]("count").innerText = counter;
}, 1000);
}
</script>

Stopping interval
js
CopyEdit
clearInterval(intervalId);

Example: Stop counter after 5 seconds


html
CopyEdit
<button onclick="stopCount()">Stop</button>

<script>
function stopCount() {
clearInterval(intervalId);
}
</script>

✅ 4️⃣Mini Project: Digital Clock


HTML
html
CopyEdit
<p id="clock"></p>

JavaScript
js
CopyEdit
function updateClock() {
let now = new Date();
let time = [Link]() + ":" + [Link]() + ":" + [Link]();
[Link]("clock").innerText = time;
}

setInterval(updateClock, 1000);

Explanation

 new Date() gets current date and time.


 setInterval() updates clock every second.

✅ 5️⃣setTimeout vs setInterval
Feature setTimeout setInterval

Runs once ✅ ❌

Runs repeatedly ❌ ✅
setTimeout(fn,
Syntax ms)
setInterval(fn, ms)

✅ 6️⃣Animation using JavaScript


Simple move animation
html
CopyEdit
<div id="box"
style="width:50px;height:50px;background:red;position:absolute;"></div>
<button onclick="move()">Move Box</button>
<script>
function move() {
let box = [Link]("box");
let pos = 0;
let id = setInterval(frame, 10);

function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
[Link] = pos + "px";
}
}
}
</script>

Explanation

 We move the box by increasing its left style property.


 The frame() function runs every 10 milliseconds.

✅ 7️⃣Basic fade-out animation


html
CopyEdit
<div id="fadeBox" style="width:100px;height:100px;background:yellow;"></div>
<button onclick="fadeOut()">Fade Out</button>

<script>
function fadeOut() {
let box = [Link]("fadeBox");
let opacity = 1;

let id = setInterval(function() {
if (opacity <= 0) {
clearInterval(id);
} else {
opacity -= 0.05;
[Link] = opacity;
}
}, 100);
}
</script>

✅ 8️⃣Chained Animations
html
CopyEdit
<div id="multiBox" style="width:100px;height:100px;background:blue;"></div>
<button onclick="animateBox()">Animate Box</button>

<script>
function animateBox() {
let box = [Link]("multiBox");
[Link] = "all 2s";
[Link] = "translateX(200px)";
setTimeout(() => {
[Link] = "orange";
}, 2000);
}
</script>

Local Storage & Session Storage (Super Detailed Content)

✅ 1️⃣Introduction to Web Storage


What is Web Storage?

Web Storage lets us store data in the browser.

 Data stays even after refresh or closing tab (local storage).


 Or data stays only during that session (session storage).

Why use Web Storage?

 Save user preferences (theme, language)


 Store form data temporarily
 Keep small app data without using a server

✅ 2️⃣Local Storage
What is local storage?
 Stores data with no expiration time
 Data persists until explicitly deleted

Basic methods

Method Use

setItem() Save value

getItem() Retrieve value

removeItem() Delete value

clear() Remove all

Example: Save name


js
CopyEdit
[Link]("username", "Alex");

Example: Get name


js
CopyEdit
let user = [Link]("username");
[Link](user);

Example: Remove
js
CopyEdit
[Link]("username");

Example: Clear all


js
CopyEdit
[Link]();
✅ 3️⃣Practical Example — Theme Toggle
HTML
html
CopyEdit
<button onclick="toggleTheme()">Toggle Dark/Light</button>

JS
js
CopyEdit
function toggleTheme() {
let mode = [Link]("mode");
if (mode === "dark") {
[Link] = "white";
[Link] = "black";
[Link]("mode", "light");
} else {
[Link] = "black";
[Link] = "white";
[Link]("mode", "dark");
}
}

// Apply on load
if ([Link]("mode") === "dark") {
[Link] = "black";
[Link] = "white";
}

Explanation

 Save mode choice in local storage.


 Apply theme automatically when page loads.

✅ 4️⃣Storing more complex data (arrays & objects)


Problem
js
CopyEdit
let colors = ["red", "blue"];
[Link]("colors", colors);
Here, it stores as string: "red,blue"

Solution: JSON
js
CopyEdit
let colors = ["red", "blue", "green"];
[Link]("colors", [Link](colors));

let stored = [Link]([Link]("colors"));


[Link](stored);

✅ 5️⃣Session Storage
What is session storage?

 Data persists only during the tab session.


 Data is cleared when tab or browser closes.

Example
js
CopyEdit
[Link]("city", "Chennai");
[Link]([Link]("city"));

Difference between local and session storage

Feature Local Storage Session Storage

Lifespan Permanent until cleared Until tab closes

Shared Shared across tabs Unique to each tab

Capacity ~5-10 MB ~5 MB

✅ 6️⃣Practical Example — Login Session


HTML
html
CopyEdit
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="login()">Login</button>
<p id="welcome"></p>

JS
js
CopyEdit
function login() {
let name = [Link]("nameInput").value;
[Link]("currentUser", name);
showWelcome();
}

function showWelcome() {
let user = [Link]("currentUser");
if (user) {
[Link]("welcome").innerText = "Welcome, " + user + "!";
}
}

showWelcome();

✅ 7️⃣Practical Example — Remembering Shopping Cart


Explanation

 Save cart items in local storage


 Retrieve on next visit

HTML
html
CopyEdit
<input type="text" id="itemInput" placeholder="Add Item">
<button onclick="addItem()">Add to Cart</button>
<ul id="cart"></ul>

JS
js
CopyEdit
let cart = [Link]([Link]("cart")) || [];
function addItem() {
let item = [Link]("itemInput").value;
[Link](item);
[Link]("cart", [Link](cart));
displayCart();
}

function displayCart() {
let list = [Link]("cart");
[Link] = "";
[Link]((item) => {
[Link] += `<li>${item}</li>`;
});
}

displayCart();

✅ 8️⃣Advanced Task — User Preferences


Options

 Font size
 Background color
 Language

Example: Save font size


js
CopyEdit
function setFontSize(size) {
[Link] = size + "px";
[Link]("fontSize", size);
}

if ([Link]("fontSize")) {
setFontSize([Link]("fontSize"));
}

✅ 9️⃣Common mistakes
 Forgetting to use JSON for objects and arrays
 Exceeding storage capacity (limit ~5 MB)
 Assuming data is secure (anyone can view storage data)
✅ 1️⃣1️⃣Text diagram: Local Storage working
pgsql
CopyEdit
User Action

JavaScript writes to local storage

Browser saves on local machine

Data persists even after refresh or close

ES6 & Modern JavaScript Features (Super Detailed


Content)

✅ 1️⃣Why ES6? (Explanation)


History

 JavaScript evolved continuously.


 ES6 (ECMAScript 2015) introduced major improvements.

Key goals

 Simpler syntax
 Avoid confusion
 Modern features for large-scale apps

✅ 2️⃣let and const


Difference from var

var let/const

Function scope Block scope

Can be redeclared Cannot redeclare (let), constants (const)


Example: Block scope
js
CopyEdit
if (true) {
let x = 10;
[Link](x); // 10
}
// [Link](x); // Error

const

 Must be initialized
 Cannot change primitive value

js
CopyEdit
const pi = 3.14;
// pi = 3.1415; // Error

For objects
js
CopyEdit
const person = { name: "Alex" };
[Link] = "Sam"; // Allowed

✅ 3️⃣Arrow functions
Syntax
js
CopyEdit
const add = (a, b) => a + b;
[Link](add(5, 7)); // 12

Block body
js
CopyEdit
const greet = (name) => {
[Link]("Hello, " + name);
};
When to use

 Short functions
 Callback functions (map, filter, forEach)

✅ 4️⃣Template literals
Syntax
js
CopyEdit
const name = "Alex";
[Link](`Welcome, ${name}!`);

Multi-line strings
js
CopyEdit
const text = `Line 1
Line 2
Line 3`;

✅ 5️⃣Default parameters
Example
js
CopyEdit
function greet(name = "Guest") {
[Link]("Hello, " + name);
}

greet(); // Hello, Guest

✅ 6️⃣Destructuring
Array destructuring
js
CopyEdit
const colors = ["red", "green", "blue"];
const [first, second] = colors;
[Link](first); // red

Object destructuring
js
CopyEdit
const person = { name: "Alex", age: 25 };
const { name, age } = person;
[Link](name); // Alex

✅ 7️⃣Spread operator (...)


Arrays
js
CopyEdit
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
[Link](arr2); // [1, 2, 3, 4, 5]

Objects
js
CopyEdit
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
[Link](obj2); // { a: 1, b: 2, c: 3 }

✅ 8️⃣Rest operator
js
CopyEdit
function sum(...args) {
return [Link]((acc, val) => acc + val, 0);
}
[Link](sum(1, 2, 3, 4)); // 10

✅ 9️⃣Enhanced object properties


js
CopyEdit
const name = "Alex";
const user = {
name,
greet() {
[Link]("Hello " + [Link]);
}
};
[Link](); // Hello Alex

✅ 🔥 Practical examples and mini tasks


Example 1: Combine arrays
js
CopyEdit
const a = [1, 2];
const b = [3, 4];
const c = [...a, ...b];
[Link](c); // [1, 2, 3, 4]

Example 2: Clone and update object


js
CopyEdit
const original = { x: 10, y: 20 };
const updated = { ...original, y: 50 };
[Link](updated); // { x: 10, y: 50 }

Example 3: Function with rest parameter


js
CopyEdit
function multiply(multiplier, ...nums) {
return [Link](n => n * multiplier);
}
[Link](multiply(2, 1, 2, 3)); // [2, 4, 6]

✅ 💥 Mini Project — Student Info Card


HTML
html
CopyEdit
<div id="card"></div>
JS
js
CopyEdit
const student = {
name: "John",
age: 21,
department: "IT"
};

const { name, age, department } = student;

[Link]("card").innerHTML = `
<h2>${name}</h2>
<p>Age: ${age}</p>
<p>Department: ${department}</p>
`;

✅ 🔥 Advanced mini project — Dynamic Menu


HTML
html
CopyEdit
<ul id="menu"></ul>

JS
js
CopyEdit
const dishes = ["Pizza", "Burger", "Pasta", "Salad"];

[Link](item => {
[Link]("menu").innerHTML += `<li>${item}</li>`;
});

🌟 — Form Validation in JavaScript (Super Detailed


Content)

✅ 1️⃣Why Validate Forms?


Explanation

 Ensure correct data is entered


 Improve security
 Prevent empty or invalid submissions
 Provide instant feedback to users

✅ 2️⃣Types of Validation
Type Description

Client-side Validation in browser using JS

Server-side Done on backend after form submit

Advantages of client-side validation

 Faster
 Reduces server load
 Immediate user feedback

✅ 3️⃣Basic HTML Form


html
CopyEdit
<form id="myForm">
<label>Name:</label>
<input type="text" id="name"><br><br>
<label>Email:</label>
<input type="text" id="email"><br><br>
<label>Password:</label>
<input type="password" id="password"><br><br>
<button type="submit">Submit</button>
</form>

<p id="error"></p>

✅ 4️⃣JavaScript Form Validation Example


js
CopyEdit
[Link]("myForm").addEventListener("submit", function(e) {
[Link]();
let name = [Link]("name").value;
let email = [Link]("email").value;
let password = [Link]("password").value;
let errorMsg = "";

if ([Link] < 3) {
errorMsg += "Name must be at least 3 characters long.<br>";
}

if (![Link]("@")) {
errorMsg += "Invalid email address.<br>";
}

if ([Link] < 6) {
errorMsg += "Password must be at least 6 characters long.<br>";
}

[Link]("error").innerHTML = errorMsg;

if (errorMsg === "") {


alert("Form submitted successfully!");
}
});

✅ 5️⃣Explanation
 We prevent default form submission using [Link]().
 Check each field and update errorMsg string.
 Display errors inside <p id="error">.

✅ 6️⃣Regular Expressions (Regex)


What is Regex?

 Used for pattern matching (emails, phone numbers, etc.).


 Syntax: /pattern/

Email validation regex


js
CopyEdit
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link](email)) {
errorMsg += "Invalid email format.<br>";
}
Password strength regex
js
CopyEdit
let strongPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
if (![Link](password)) {
errorMsg += "Password must include uppercase, lowercase, and a number.<br>";
}

✅ 7️⃣Example: Phone number validation


js
CopyEdit
let phone = [Link]("phone").value;
let phoneRegex = /^[0-9]{10}$/;

if (![Link](phone)) {
errorMsg += "Phone number must be 10 digits.<br>";
}

✅ 8️⃣Disable submit button


js
CopyEdit
const submitBtn = [Link]("button[type='submit']");
[Link] = true;

[Link]("password").addEventListener("input", function() {
if ([Link] >= 6) {
[Link] = false;
} else {
[Link] = true;
}
});

✅ 9️⃣Styling errors with CSS


html
CopyEdit
<style>
#error {
color: red;
}
[Link]-border {
border: 2px solid red;
}
</style>
js
CopyEdit
if ([Link] < 3) {
[Link]("name").[Link]("error-border");
} else {
[Link]("name").[Link]("error-border");
}

✅ 🔥 Mini Project — Sign-up Form Validation


HTML
html
CopyEdit
<form id="signupForm">
<input type="text" id="username" placeholder="Username"><br><br>
<input type="email" id="signupEmail" placeholder="Email"><br><br>
<input type="password" id="signupPass" placeholder="Password"><br><br>
<input type="password" id="confirmPass" placeholder="Confirm
Password"><br><br>
<button type="submit">Register</button>
<p id="signupError"></p>
</form>

JS
js
CopyEdit
[Link]("signupForm").addEventListener("submit", function(e) {
[Link]();
let username = [Link]("username").value;
let email = [Link]("signupEmail").value;
let pass = [Link]("signupPass").value;
let confirmPass = [Link]("confirmPass").value;
let msg = "";

if ([Link] < 3) msg += "Username too short.<br>";


if (![Link]("@")) msg += "Invalid email.<br>";
if ([Link] < 6) msg += "Password too short.<br>";
if (pass !== confirmPass) msg += "Passwords do not match.<br>";

[Link]("signupError").innerHTML = msg;

if (msg === "") {


alert("Successfully registered!");
}
});

You might also like