element's click event.
+
+// In capturing the outer most element's event is handled first and then the inner: the
element's click event will be handled first, then the
element's click event.
+
+// With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
+
+// addEventListener(event, function, useCapture);
+// The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.
+
+// Example
+// document.getElementById("myP").addEventListener("click", myFunction, true);
+// document.getElementById("myDiv").addEventListener("click", myFunction, true);
+// The removeEventListener() method
+// The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
+
+// Example
+// element.removeEventListener("mousemove", myFunction);
+
+
+// Use the eventListener to assign an onclick event to the element.
+
+
+// Click me1
+
+//
+
+
+// JavaScript HTML DOM Navigation
+// With the HTML DOM, you can navigate the node tree using node relationships.
+
+// DOM Nodes:
+
+// According to the W3C HTML DOM standard, everything in an HTML document is a node:
+
+// The entire document is a document node
+// Every HTML element is an element node
+// The text inside HTML elements are text nodes
+// Every HTML attribute is an attribute node (deprecated)
+// All comments are comment nodes
+// DOM HTML tree
+
+// Image:https://www.w3schools.com/js/pic_htmltree.gif
+
+// With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
+
+// New nodes can be created, and all nodes can be modified or deleted.
+
+// Node Relationships
+// The nodes in the node tree have a hierarchical relationship to each other.
+
+// The terms parent, child, and sibling are used to describe the relationships.
+
+// In a node tree, the top node is called the root(or root node)
+// Every node has exactly one parent, except the root(which has no parent)
+// A node can have a number of children
+// Siblings(brothers or sisters) are nodes with the same parent
+//Image:https://www.w3schools.com/js/pic_navigate.gif
+
+// < html >
+
+//
+// DOM Tutorial
+//
+
+//
+// DOM Lesson one
+// Hello world!
+//
+
+//
+
+// From the HTML above you can read:
+
+// is the root node
+// has no parents
+// is the parent of and
+// is the first child of
+// is the last child of
+// and:
+
+// has one child:
+// has one child (a text node): "DOM Tutorial"
+// has two children: and
+//
has one child: "DOM Lesson one"
+// has one child: "Hello world!"
+//
and are siblings
+
+// Navigating Between Nodes
+
+
+// You can use the following node properties to navigate between nodes with JavaScript:
+
+// parentNode
+// childNodes[nodenumber]
+// firstChild
+// lastChild
+// nextSibling
+// previousSibling
+// Child Nodes and Node Values
+// A common error in DOM processing is to expect an element node to contain text.
+
+// Example:
+
+//
DOM Tutorial
+
+// The element node (in the example above) does not contain text.
+
+// It contains a text node with the value "DOM Tutorial".
+
+// The value of the text node can be accessed by the node's innerHTML property:
+
+// myTitle = document.getElementById("demo").innerHTML;
+// Accessing the innerHTML property is the same as accessing the nodeValue of the first child:
+
+// myTitle = document.getElementById("demo").firstChild.nodeValue;
+// Accessing the first child can also be done like this:
+
+// myTitle = document.getElementById("demo").childNodes[0].nodeValue;
+// All the (3) following examples retrieves the text of an element and copies it into a element:
+
+Example:
+
+//
+//
+
+// My First Page
+//
+
+//
+
+//
+//
+
+
+Example:
+
+//
+//
+
+// My First Page
+//
+
+//
+
+//
+//
+
+Example:
+
+//
+//
+
+// My First Page
+// Hello!
+
+//
+
+//
+//
+
+
+// InnerHTML
+// In this tutorial we use the innerHTML property to retrieve the content of an HTML element.
+
+// However, learning the other methods above is useful for understanding the tree structure and the navigation of the DOM.
+
+// DOM Root Nodes
+// There are two special properties that allow access to the full document:
+
+// document.body - The body of the document
+// document.documentElement - The full document
+
+
+Example:
+
+//
+//
+
+// JavaScript HTMLDOM
+// Displaying document.body
+
+//
+
+//
+
+//
+//
+
+
+Example:
+
+//
+//
+
+// JavaScript HTMLDOM
+// Displaying document.documentElement
+
+//
+
+//
+
+//
+//
+
+// The nodeName Property
+// The nodeName property specifies the name of a node.
+
+// nodeName is read-only
+// nodeName of an element node is the same as the tag name
+// nodeName of an attribute node is the attribute name
+// nodeName of a text node is always #text
+// nodeName of the document node is always #document
+
+Example:
+
+
+// My First Page
+//
+
+//
+// Note: nodeName always contains the uppercase tag name of an HTML element.
+
+// The nodeValue Property
+// The nodeValue property specifies the value of a node.
+
+// nodeValue for element nodes is null
+// nodeValue for text nodes is the text itself
+// nodeValue for attribute nodes is the attribute value
+// The nodeType Property
+// The nodeType property is read only. It returns the type of a node.
+
+Example:
+
+
+// My First Page
+//
+
+//
+// The most important nodeType properties are:
+
+// Node Type Example:
+
+// ELEMENT_NODE 1 W3Schools
+// ATTRIBUTE_NODE 2 class = "heading" (deprecated)
+// TEXT_NODE 3 W3Schools
+// COMMENT_NODE 8
+// DOCUMENT_NODE 9 The HTML document itself (the parent of )
+// DOCUMENT_TYPE_NODE 10
+
+
+// JavaScript HTML DOM Elements (Nodes)
+// Adding and Removing Nodes (HTML Elements)
+
+// Creating New HTML Elements (Nodes)
+// To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
+
+Example:
+
+
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+
+//
+
+
+Example Explained:
+
+
+// This code creates a new element:
+
+// const para = document.createElement("p");
+// To add text to the
element, you must create a text node first. This code creates a text node:
+
+// const node = document.createTextNode("This is a new paragraph.");
+// Then you must append the text node to the
element:
+
+// para.appendChild(node);
+// Finally you must append the new element to an existing element.
+
+// This code finds an existing element:
+
+// const element = document.getElementById("div1");
+// This code appends the new element to the existing element:
+
+// element.appendChild(para);
+// Creating new HTML Elements - insertBefore()
+// The appendChild() method in the previous example, appended the new element as the last child of the parent.
+
+// If you don't want that you can use the insertBefore() method:
+
+Example:
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+
+//
+
+
+// Removing Existing HTML Elements
+// To remove an HTML element, use the remove() method:
+
+Example:
+
+
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+
+//
+// Example Explained
+// The HTML document contains a element with two child nodes (two
elements):
+
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+
+
+// Find the element you want to remove:
+
+// const elmnt = document.getElementById("p1");
+// Then execute the remove() method on that element:
+
+// elmnt.remove();
+// The remove() method does not work in older browsers, see the example below on how to use removeChild() instead.
+
+// Removing a Child Node
+// For browsers that does not support the remove() method, you have to find the parent node to remove an element:
+
+Example:
+
+
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+
+//
+
+
+// Example Explained
+// This HTML document contains a
element with two child nodes (two
elements):
+
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+// Find the element with id="div1":
+
+// const parent = document.getElementById("div1");
+// Find the
element with id="p1":
+
+// const child = document.getElementById("p1");
+// Remove the child from the parent:
+
+// parent.removeChild(child);
+// Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
+
+// const child = document.getElementById("p1");
+// child.parentNode.removeChild(child);
+// Replacing HTML Elements
+// To replace an element to the HTML DOM, use the replaceChild() method:
+
+Example:
+
+
+//
+//
This is a paragraph.
+//
This is another paragraph.
+//
+
+//
+
+
+// JavaScript HTML DOM Collections
+// The HTMLCollection Object
+
+
+// The getElementsByTagName() method returns an HTMLCollection object.
+
+// An HTMLCollection object is an array-like list (collection) of HTML elements.
+
+// The following code selects all
elements in a document:
+
+Example:
+
+
+// const myCollection = document.getElementsByTagName("p");
+// The elements in the collection can be accessed by an index number.
+
+// To access the second
element you can write:
+
+// myCollection[1]
+// Note: The index starts at 0.
+
+// HTML HTMLCollection Length
+// The length property defines the number of elements in an HTMLCollection:
+
+Example:
+
+// myCollection.length
+// The length property is useful when you want to loop through the elements in a collection:
+
+Example:
+
+// Change the text color of all
elements:
+
+// const myCollection = document.getElementsByTagName("p");
+// for (let i = 0; i < myCollection.length; i++) {
+// myCollection[i].style.color = "red";
+// }
+// An HTMLCollection is NOT an array!
+
+// An HTMLCollection may look like an array, but it is not.
+
+// You can loop through the list and refer to the elements with a number (just like an array).
+
+// However, you cannot use array methods like valueOf(), pop(), push(), or join() on an HTMLCollection.
+
+
+// JavaScript HTML DOM Node Lists
+// The HTML DOM NodeList Object
+// A NodeList object is a list (collection) of nodes extracted from a document.
+
+// A NodeList object is almost the same as an HTMLCollection object.
+
+// Some (older) browsers return a NodeList object instead of an HTMLCollection for methods like getElementsByClassName().
+
+// All browsers return a NodeList object for the property childNodes.
+
+// Most browsers return a NodeList object for the method querySelectorAll().
+
+// The following code selects all
nodes in a document:
+
+// Example
+// const myNodeList = document.querySelectorAll("p");
+// The elements in the NodeList can be accessed by an index number.
+
+// To access the second
node you can write:
+
+// myNodeList[1]
+// Note: The index starts at 0.
+
+// HTML DOM Node List Length
+// The length property defines the number of nodes in a node list:
+
+// Example
+// myNodelist.length
+// The length property is useful when you want to loop through the nodes in a node list:
+
+// Example
+// Change the color of all
elements in a node list:
+
+// const myNodelist = document.querySelectorAll("p");
+// for (let i = 0; i < myNodelist.length; i++) {
+// myNodelist[i].style.color = "red";
+// }
+// The Difference Between an HTMLCollection and a NodeList
+// A NodeList and an HTMLcollection is very much the same thing.
+
+// Both are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0.
+
+// Both have a length property that returns the number of elements in the list (collection).
+
+// An HTMLCollection is a collection of document elements.
+
+// A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes).
+
+// HTMLCollection items can be accessed by their name, id, or index number.
+
+// NodeList items can only be accessed by their index number.
+
+// An HTMLCollection is always a live collection. Example: If you add a
element to a list in the DOM, the list in the HTMLCollection will also change.
+
+// A NodeList is most often a static collection. Example: If you add a element to a list in the DOM, the list in NodeList will not change.
+
+// The getElementsByClassName() and getElementsByTagName() methods return a live HTMLCollection.
+
+// The querySelectorAll() method returns a static NodeList.
+
+// The childNodes property returns a live NodeList.
+
+// Not an Array!
+// A NodeList may look like an array, but it is not.
+
+// You can loop through a NodeList and refer to its nodes by index.
+
+// But, you cannot use Array methods like push(), pop(), or join() on a NodeList.
diff --git a/Ch 7 DOM Practice Set.js b/Ch 7 DOM Practice Set.js
new file mode 100644
index 0000000..5695ebf
--- /dev/null
+++ b/Ch 7 DOM Practice Set.js
@@ -0,0 +1,68 @@
+// Ch 7 DOM Practice Set
+
+// Q1: How can you access an HTML element by its unique ID?
+// A: By using the getElementById method. For example:
+
+const element = document.getElementById('myElement');
+
+
+// Q2: How can you access HTML elements based on their class name?
+// A: By using the getElementsByClassName method. For example:
+
+const elements = document.getElementsByClassName('myClass');
+
+
+// Q3: How can you access HTML elements based on their tag name?
+// A: By using the getElementsByTagName method. For example:
+
+const elements = document.getElementsByTagName('h1');
+
+
+// Q4: How can you access HTML elements using CSS selectors?
+// A: By using the querySelector method. For example:
+
+const element = document.querySelector('.mySelector');
+
+
+// Q5: How can you modify the content of an HTML element?
+// A: By using the innerHTML property. For example:
+
+const myDiv = document.getElementById('myDiv');
+myDiv.innerHTML = 'Hello, JavaScript!';
+
+
+// Q6: How can you modify the attributes of an HTML element?
+// A: By using the setAttribute method. For example:
+
+const myImage = document.getElementById('myImage');
+myImage.setAttribute('src', 'new_image.jpg');
+
+
+// Q7: How can you modify the styles of an HTML element?
+// A: By using the style property. For example:
+
+const myDiv = document.getElementById('myDiv');
+myDiv.style.backgroundColor = 'red';
+
+
+// Q8: How can you add a class to an HTML element?
+// A: By using the classList.add method. For example:
+
+const myDiv = document.getElementById('myDiv');
+myDiv.classList.add('highlight');
+
+
+// Q9: How can you create a new HTML element and append it to the document?
+// A: By using the createElement and appendChild methods. For example:
+
+const newParagraph = document.createElement('p');
+newParagraph.innerHTML = 'This is a new paragraph.';
+document.body.appendChild(newParagraph);
+
+
+// Q10: How can you check if an element contains another element as a descendant?
+// A: By using the contains method. For example:
+
+const parentElement = document.getElementById('parent');
+const childElement = document.getElementById('child');
+const isChildOfParent = parentElement.contains(childElement);
\ No newline at end of file
diff --git a/Ch 7 Js DOM.js b/Ch 7 Js DOM.js
new file mode 100644
index 0000000..6a75431
--- /dev/null
+++ b/Ch 7 Js DOM.js
@@ -0,0 +1,138 @@
+// HTML Ko Convert Kar Diya He Js Object Me -> All Node Are Object
+// Text Node
+// Element Node
+// Comment Node
+
+// Auto Correction In HTML -> If Any Error In HTML Then It Will Be Auto Corrected
+
+// Walking The DOM
+
+// DOM Tree Traversal
+// document.body -> Page Body Tag
+// document.documentElement -> HTML Tag -> Page
+// document.head -> Head Tag
+// document.title -> String
+
+// document.body can be Null If The JavaScript Is Written Before The Body Tag
+// Children Of An Element -> Direct As Well As Deeply Nested Elements Of An Element Are Called Its Children
+
+// Child Nodes: Elements That Are Direct Children For Example Head And Body Are Children Of
+
+// Descendant Nodes: All Necessary Nodes Are Called Descendant Nodes For Example Head, Body, Title, Meta, Etc. Are Descendant Nodes Of
+
+// All Nested Elements , CHildren , Their Children And So On Are Called Their Siblings
+
+// First Child -> First Element Child -> element.firstChild
+// Last Child -> Last Element Child -> element.lastChild
+// Child Nodes (Element.childNodes) -> All Children
+
+// Following Are Always True
+// element.firstChild === element.childNodes[0]
+// element.lastChild === element.childNodes[element.childNodes.length - 1]
+
+// There Is Also A Method Element.hasChildNodes() To Check Whether There Are Any Child Nodes (Element.childNodes) Or Not
+
+// Child Nodes Are Not An Array But Can Be Converted Into Array -> Array.from(collection)
+
+// Child Nodes Look Like An Array But Actually Are Not But Its A Collection -> We Can Use Array Methods On It By Converting It Into Array.from(collection) To Convert It Into Array -> Array Methods Will Not Work On It
+
+// Notes On Dom Collection
+// They Are Read Only
+// They Are Live Element.childNodes Variable (Reference) Will Be Updated Automatically If Child Nodes Of The Element Is Changed
+// They Are Iterable Using For...Of Loop
+
+// Siblings And Their Parents
+
+// Siblings Are Nodes That Are Children Of The Same Parent
+// For Example And Are Siblings. Siblings Have Same Parent In This Case
+// Is Said To Be The "Next" Or "Right" Sibling Of , Is Said To Be The "Previous" Or "Left" Sibling Of
+// The Next Sibling Is In NextSibling Property , And The Previous One Is In previousSibling Property
+// The Parent Is In parentNode Property
+// alert(document.documentElement.parentNode) -> Document
+// alert(document.documentElement.parentElement) -> Null
+// parentElement -> Ak Element Hai To Hi Return Hoga Verna Null Return Hoga
+
+// console.log(document.body.firstChild)
+// a = document.body.firstChild
+// console.log(a.parentNode)
+// console.log(a.parentElement)
+// console.log(a.firstChild.nextSibling)
+
+
+
+// Element Only Navigation
+
+// Sometimes We Don't Want Text Or Comment Nodes. Some Links Only Take Element Nodes Into Account. For Example -> document.previousElementSibling -> Previous Sibling Which Is An Element
+
+
+// let b = document.body
+// console.log("First Child Of b Is : ", b.firstChild) // -> Kisi Bhi Tarah Ka First Childe Dekhne Ko Mil Sakta He Chahe Vo text Node Hi Kyu Na Ho
+// console.log("First Element Child Of b Is : ", b.firstElementChild)
+// Only Element Type Ka First Child Dekhne Ko Milta He
+
+// const changeBgRed =()=>{
+// document.body.firstElementChild.style.background = "red"
+
+// }
+
+// document.previousElementSibling -> Previous Sibling Which Is An Element
+// document.nextElementSibling -> Next Sibling Which Is An Element
+// document.firstElementChild -> First Element Child
+// document.lastElementChild -> Last Element Child
+
+// Table Links
+// Certain DOM Elements May Provide Additional Properties Specific To Their Type For Example Table Elements Support -> table.rows -> Collection Of Tr Elements
+
+// table.rows -> Collection Of Tr Elements
+// table.caption -> Reference To
+// table.tHead -> Reference To
+// table.tFoot -> Reference To
+// table.tBodies -> Collection Of Elements
+// tbody.rows -> Collection Of Inside
+// tr.cells -> Collection Of Td And Th
+// tr.sectionRowIndex -> Index Of Tr In It's Section
+// tr.rowIndex -> Row Number Starting From 0
+// td.cellIndex -> No Of Cells In Row
+
+
+// Searching The DOM
+// document.getElementById() -> To Search Element By Id
+// document.querySelectorAll(.card-title) -> To Search Multiple Elements With Same CSS Selector
+// document.querySelector() -> To Search Single Element With CSS Selector
+// document.getElementsByTagName() -> To Search Element By Tag Name
+// document.getElementsByClassName() -> To Search Element By Class Name
+// document.getElementsByName() -> To Search Element By Name Attribute
+
+// let ctitle = document.getElementsByClassName("card-title")[0]
+// console.log(document.quarySelector(".card-title").getElemetByClassName("card-title"))
+
+// No S -> Return One Element
+// S -> Return All Elements -> Elements
+
+// Matches, Closest & Contains Methods
+// elem.matches(CSS) -> To Check If Element Matches The Given CSS Selector
+// elem.closest(CSS) -> To Look For The Nearest ancestor That Matches The Given CSS Selector.
+// No Than Go to Perent Hai TO Return So And So
+
+// let id1 = document.getElementById("id1")
+// let sp1 = document.getElementById("sp1")
+// console.log(id1.matches(".class"))
+
+// elem.contains(elem) -> Returns True If Element B Is Inside Element A (A Descendant Of B) Or When Element A == Element B
+
+
+// Chapter 7 Practice Set
+// Q1 -> Create A Navbar And Change The Color Of Its First Element To Red
+// document.getElementsByTagName("nav")[0].firstElementChild.style.color = "red"
+// Q2 -> Create A Table Using JavaScript Which Background Color To Green
+// document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
+// Q3 -> Create An Element With 3 Children. Now Change The Color Of First And Last Element To Green
+// document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
+// document.getElementsByTagName("nav")[0].lastElementChild.style.color = "green"
+// Q4 -> Write A JavaScript Code To Change Background Of All Tags To Cyan
+// Array.from(document.getElementsByTagName("li")).forEach((element) => {
+// element.style.background = "cyan";
+// })
+// Q5 -> Which Of The Following Is Used To Look For The Farthest Ancestor That Matches A Given CSS Selector
+// (a) matches (b) closest (c) contains (d) none of these
+// Ans -> None Of These
diff --git a/Ch 8 Event & Other DOM Properties.js b/Ch 8 Event & Other DOM Properties.js
new file mode 100644
index 0000000..f69e864
--- /dev/null
+++ b/Ch 8 Event & Other DOM Properties.js
@@ -0,0 +1,97 @@
+// Event & Other DOM Properties
+
+// Event Handling
+// Now, let's discuss Event Handling using Javascript:
+// Event Handling:
+// Event handling in JavaScript with the HTML DOM
+// (Document Object Model) allows you to respond
+// to user interactions or other events that occur on
+// a webpage
+
+
+// Event Types:
+// Events can be triggered by various actions, such as a user
+// clicking a button, hovering over an element, submitting a
+// form, or even the page finishing loading. Some common
+// event types include click, mouseover, submit, keydown,
+// and load. You can attach event handlers to these events
+// to execute JavaScript code when the event occurs. like
+// this:
+Click me
+
+var button = document.getElementById("myButton");
+// Event handler for the click event
+button.addEventlistener("click", function() f
+alert("Button clicked!");
+});
+
+// This code finds a button on a web page, listens for a
+// click on that button, and when the click happens, it
+// shows a pop-up message saying 'Button clicked!" to
+// let the user know that the button was indeed
+// clicked.
+
+
+// Attaching Event Handlers:
+// To attach an event handler to an element, you can use
+// the addEventListener method. This method takes the
+// event type as the first argument and a callback
+// function as the second argument. The callback function
+// is executed when the event is triggered.Like this:
+
+var button = document.getElementById("myButton");
+// Event handler for the click event
+function handleClick() {
+}
+alert("Button clicked!");
+// Attach the event handler to the button
+button.addEventListener("click", handleClick);
+
+// This code finds a button on a web page, defines a function
+// that displays an alert when the button is clicked, and attaches
+// that function as an event handler to the button. When the
+// button is clicked, the function is triggered, and an alert box
+// pops up with the message "Button clicked!" to let the user
+// know that the button was clicked.
+
+
+// Removing Event Handlers:
+// If you no longer need an event handler, you can remove it
+// using the removeEventListener method. This method
+// requires the same event type and callback function that were
+// used to attach the event handler.
+
+var button = document.getElementById("myButton");
+// Event handler for the click event
+function handleclick() {
+ alert("Button clicked!");
+}
+// Attach the event handler to the button
+button.addEventListener("click", handleClick);
+// Remove the event handler from the button
+button.removeEventlistener("click", handleClick);
+
+// This code attaches a click event handler to a button element with the
+// id "'myButton". When the button is clicked, an alert saying "Button
+// clicked!" will be shown.
+// Later, the event handler is removed from the button using the
+// removeEventListener method. This means that when the button is
+// clicked again, the handleClick function will no longer be executed.
+
+// Example:
+
+// Click me
+
+//
+
+{/* output
+127.0.0.1:5501 says
+Button clicked!
+OK
+Click me */}
\ No newline at end of file
diff --git a/Ch 8 Events And Other DOM Properties.js b/Ch 8 Events And Other DOM Properties.js
new file mode 100644
index 0000000..7576984
--- /dev/null
+++ b/Ch 8 Events And Other DOM Properties.js
@@ -0,0 +1,288 @@
+// console.log(document.getElementsByTagName('span')[0])
+// console.dir(document.getElementsByTagName('span')[0]) // -> Span Ko Object Dikhayega With Its Properties
+
+// console.log -> Shows the element DOM tree
+// console.dir -> Shows the element as an object with its properties
+
+// console.log(document.body.firstChild.nodeName)
+// console.log(document.body.firstElementChild.nodeName)
+
+// TagName/ NodeName
+// TagName -> Only Exists For Element Nodes
+// NodeName -> Defined For Any Node (Text, Comment, etc)
+
+// innerHTML / outerHTML
+// innerHTML -> The Inner HTML Property allows to get the HTML inside the element as a string. -> Work For Element Nodes Only
+
+// outerHTML -> The outerHTML property contains the full HTML. -> Work For All Nodes
+
+// outerHTML Property Contain The Full HTML innerHTML + The Element Itself
+// first.innerHtml -> Help In Get Or Set The Inner HTML
+// first.innerHtml = "Hey I Am Italic " -> Insertion
+
+// first.outerHTML -> Help In Get Or Set The Outer HTML
+// Output -> Hey I Am Italic
+
+
+// document.body.firstChild.data -> Gives The Data Of The First Child
+// document.body.firstChild.nodeValue -> Same As Data
+
+// Text Content
+// The textContent property allows to get the text inside the element as a string. Only Works For Element Nodes
+
+// console.log(document.body.textContent)
+
+// Hidden Property
+// The hidden attribute and the DOM property specifies whether the element is visible or not.
+// first.hidden = false -> Shows The Element
+// first.hidden = true -> Hides The Element
+
+// Attributes Method
+// 1. elem.hasAttribute(name) -> Method To Check For Existence Of An Attribute
+// 2. elem.getAttribute(name) -> Method Used To Get The Value Of An Attribute
+// 3. elem.setAttribute(name, value) -> Method Used To Set The Value Of An Attribute
+// 4. elem.removeAttribute(name) -> Method Used To Remove The Attribute From Element
+// 5. elem.attributes -> Method To Get The Collection Of All Attributes
+// Data-* Attributes
+// We Can Always Create Custom Attributes But The One Starting With "data-" Are Reserved For Programmer Use. They Are Available In A Property Named dataset
+// If An Element Has An Attribute Named "data-one" -> The Way To Access This Attribute Is : elem.dataset.one
+
+
+// let a = first.getAttribute("class")
+// console.log(a)
+
+
+// console.log(first.hasAttribute("class"))
+// console.log(first.hasAttribute("style"))
+// // first.setAttribute("hidden", "true")
+// first.setAttribute("class", "true sachin")
+// first.removeAttribute("class")
+// console.log(first.attributes)
+// console.log(first.dataset)
+// console.log(first.dataset.game)
+// console.log(first.dataset.player)
+
+
+// Always Add Custom Attribute With Data-_____
+// Data Attributes
+// data-one = "one" -> data-one -> One
+// data-game = "mario" -> data-game -> Mario
+
+// If Element Has A Attribute Named "data-one" -> The Way To Access This Attribute Is : elem.dataset.one
+
+// Insertion Method
+
+// There Are Three Way To Insert HTML Into The DOM
+
+// 1. innerHTML
+
+// let a = document.getElementsByTagName('div')[0]
+// a.innerHTML = a.innerHTML + 'Hello World! ';
+
+
+// 2. document.createElement()
+// let div = document.createElement('div');
+// div.innerHTML = 'Hello World! ';
+// a.appendChild(div);
+// div.className = "alert"
+// We Can Use For Loop In This Case
+
+// 3. document.createTextNode()
+// let div = document.createTextNode('This Is Text Node');
+// a.appendChild(div);
+
+// Node Insertion Method
+// 4. node.append(e) -> Append At The End Of Node
+
+// 5. node.prepend() -> Insert At The Beginning Of Node
+
+// 6. node.before() -> Insert Before Node
+
+// 7. node.after() -> Insert After Node
+
+// 8. node.replaceWith() -> Replace Node With Another Node
+
+// Insert Adjacent HTML / Text / Element
+
+// first.insertAdjacentHTML('beforebegin', 'beforebegin
');
+// first.insertAdjacentHTML('beforeend', 'beforeend
');
+// first.insertAdjacentHTML('afterbegin', 'afterbegin
');
+// first.insertAdjacentHTML('afterend', 'afterend
');
+
+// Node Removal
+// first.remove() -> Remove The Element
+
+
+// ClassName & ClassList
+// className -> Used To Add/Remove/Toggle A Class
+// classList -> Used To Add/Remove/Toggle A Class
+// first.className = "text-black red"
+// first.classList.remove("red") // Remove Karva
+// first.classList.add("red") // Add Karva
+// first.classList.toggle("red") // He To Hata Dega Nahi He to Laga Dega
+// first.classList.contains("red") // Check If Contain Or Not? -> True False
+
+// SetTimeout And SetInterval
+
+// setTimeout(function, , , )
+// setTimeOut -> Kuch Time Ke Bad Apni JS Ko excute Karna Hoga -> Excute The Js After Certain Time
+// clearTimeout -> To Clear The SetTimeout
+// setInterval -> In Certain Interval Of Time Hame Bar Bar Apni Js Ko Excute Karna Hoga -> Excute The Js After Certain Time(Interval)
+// setTimeout -> Is Function Ko Run Kardo Itne Time Ke Bad
+
+// alert("Hello")
+// let a = setTimeout(function() {
+// alert("I Am Inside Of SetTimeout")
+// }, 2000)
+// clearTimeout(a)
+// console.log(a) // Timer Id
+
+// let timerId = setInterval(function, , , )
+// Delay In millisecond
+// Timer Id Return Me Milti He
+
+// const sum = (a, b, c) => (){
+// console.log("Yes I Am Running " + (a + b + c))
+// a + b
+// }
+
+// setTimeout(sum, 1000, 1, 2, 7)
+// clearTimeout(timerId)
+
+// setInterval -> Bar Bar Kuch Time Ke Bad Run Karna
+// Syntex -> setInterval(function, , , )
+
+// Example:
+// let a = setInterval(function() {
+// console.log("I Am In SetInterval")
+// }, 3000)
+
+
+// clearInterval(a) -> To Clear The SetInterval
+
+// Browser Events
+
+// An Event Is A Signal That Something Has Happened.
+// All Dom Node Generate Such Signal
+
+// Mouse Events -> click, contextmenu, mouseover/mouseout, mousedown/mouseup, mousemove
+
+// Keyboard Events -> keydown and keyup
+// Form Element Events -> submit, focus
+// Document Events -> DOMContentLoaded
+
+// Click Me
+
+// Handling Events
+// elem.onclick = function(e){
+// alert("Hello World1!")
+// }
+
+// let a = document.getElementsByClassName("container")[0]
+// console.log(a)
+// a.onclick = () => {
+// let b = document.getElementsByClassName("container")[0]
+// b.innerHTML = "Hello World!"
+// }
+
+// If Onclick Js and HTML Me Likha Hai To Js Vala Priorty Hota Hai
+
+// Adding A Handler With JavaScript Overwrite The Existing Handler
+
+// Event Listener
+
+// addEventListener(event, handler) and removeEventListener(event, handler)
+
+// Handler Must Be Same While Removing It
+
+// addeventListener -> To Assign Multiple Handlers To An Event
+
+// let x = function(e) {
+// alert("Hello World1!")
+// }
+// let y = function(e) {
+// console.log(e) // Event Object -> Pointing To The Our Function
+// // console.log(e.target)
+// alert("Hello World2!")
+// }
+// btn.addEventListener('click', x)
+
+// btn.addEventListener('click', function(e) {
+// alert("Hello World2!")
+// })
+
+// btn.addEventListener('click', y)
+
+// let a = prompt("What is Your Favorite Number?");
+// if (a == "2") {
+// btn.removeEventListener('click', x)
+// }
+
+// For This Work FUnction OBject Same Hona Cahiye -> Means That We Want to Remove Function y than We Must Pass The Function y So That Function Object Can Removed
+
+
+// Event Object
+
+// When An Event Happens, The Browser Creates An Event Object, Put Details In It And Pass It As And Passes It As An Argument To The Handler
+
+// elem.onclick = function(event){
+// Code
+// }
+
+// event.type -> Event Type
+// event.currentTarget -> Element That Handled The Event
+// event.clientX/ event.clientY -> Coordinates Of Cursor
+
+
+// Practice Set
+
+// Q1 -> Create A Website Which Stores Bookmarks Of Your Favorite Website Using href
+// Ans: Ans On HTML File
+// Q2 -> Write A Program To Show Different Alerts When Different Buttons Are Clicked
+// Ans: Ans On HTML File
+// Q3 -> Create A Website Which Stores Bookmarks Of Your Favorite Website Using Event Listeners
+// document.getElementById("google").addEventListener("click", function() {
+// window.location = "https://www.google.com";
+// win.focus();
+// })
+// document.getElementById("fb").addEventListener("click", function() {
+// window.location = "https://www.facebook.com";
+// win.focus();
+// })
+// document.getElementById("twitter").addEventListener("click", function() {
+// window.location = "https://www.twitter.com";
+// win.focus();
+// })
+// document.getElementById("insta").addEventListener("click", function() {
+// window.location = "https://www.instagram.com";
+// win.focus();
+// })
+
+
+// Q4 -> Write A JavaScript Program To Keep fetching contents of a website (Every 5 Seconds)
+
+// setInterval(async function() {
+// let url = "https://jsonplaceholder.typicode.com/todos/1"
+// console.log(await fetchContent(url))
+// },3000)
+
+// const fetchContent = async (url) =>{
+// con = await fetch(url);
+// let a = await con.json()
+// return a;
+// }
+
+// Q5 -> Create A Glowing Bulb Effect Using ClassList Toggle Method In JavaScript
+
+
+// setInterval(async function(){
+// document.querySelector("#bulb").classList.toggle("bulb")
+// },300)
+
+// Clock
+
+// let a = new Date()
+// let h = a.getHours()
+// let m = a.getMinutes()
+// let s = a.getSeconds()
+
diff --git a/Ch 9 Callbacks, Promises And Async And Await.js b/Ch 9 Callbacks, Promises And Async And Await.js
new file mode 100644
index 0000000..81cde1a
--- /dev/null
+++ b/Ch 9 Callbacks, Promises And Async And Await.js
@@ -0,0 +1,834 @@
+// Ch 9 Callbacks, Promises And Async/Await
+// Asynchronous Action Are Action That We Initiate Now And They Finish Later. E.g. SetTimeout
+// Synchronous Action Are Action That Initiate And Finish One By One.
+
+// Callbacks Function
+// A Callback Function Is A Function Passed Into Another Function As An Argument, Which Is Then Invoked Inside The Outer Function To Complete An Action.
+
+// Here Is Example Of callback
+// function loadScript(src, callback) {
+// let script = document.createElement("script");
+// script.src = src;
+// script.onload = function() {
+// console.log("Loaded Script With SRC: " + src);
+// callback(null, src);
+// };
+// script.onerror = function() {
+// console.log("Error Loading Script With SRC: " + src);
+// callback(new Error("Src got some error"));
+// This Will Show What is Exactly The Error
+// };
+// document.body.appendChild(script);
+// }
+
+
+// Ch 9 Callbacks, Promises And Async/Await
+// Asynchronous Action Are Action That We Initiate Now And They Finish Later. E.g. SetTimeout
+// Synchronous Action Are Action That Initiate And Finish One By One.
+
+// Callbacks Function
+// A Callback Function Is A Function Passed Into Another Function As An Argument, Which Is Then Invoked Inside The Outer Function To Complete An Action.
+
+// Here Is Example Of callback
+// function loadScript(src, callback) {
+// let script = document.createElement("script");
+// script.src = src;
+// script.onload = function() {
+// console.log("Loaded Script With SRC: " + src);
+// document.head.append(script)
+// callback(null, src);
+// }
+// script.onerror = function() {
+// console.log("Error Loading Script With SRC: " + src);
+// };
+// document.body.appendChild(script);
+// }
+
+// function hello() {
+// alert("Hello World");
+// }
+
+// function goodmorning() {
+// alert("Good Morning");
+// }
+
+// loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css", hello)
+
+// This Is Call Back Of Asynchronous Programming. A function Does Something Asynchronously Should Provide A Callback Function As An Argument. Where We Put The Code That We Want To Run After Some Action Has Been Performed.
+
+// Handling Error :
+
+
+
+// // Callbacks
+// function loadScript(src, callback) {
+// var script = document.createElement("script");
+// script.src = src;
+// script.onload = function() {
+// console.log("Loaded script with SRC: " + src)
+// callback(null, src);
+// }
+// script.onerror = function() {
+// console.log("Error loading script with SRC: " + src);
+// callback(new Error("Src got some error"))
+// }
+// document.body.appendChild(script);
+// }
+
+// function hello(error, src) {
+// if (error) {
+// console.log(error)
+// return
+// }
+// alert('Hello World!' + src);
+// }
+
+
+// function goodmorning(error, src) {
+
+// if (error) {
+// console.log(error)
+// sendEmergencyMessageToCeo();
+// return
+// }
+// alert('Good morning' + src);
+// }
+
+// loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js", goodmorning)
+
+// Function
+// function greet(name, callback) {
+// console.log('Hi' + ' ' + name);
+// callback();
+// }
+// // Callback Function
+// function callMe() {
+// console.log('I am callback function');
+// }
+
+// // Passing function as an argument
+// greet('Peter', callMe);
+
+// const calculate = (a, b, operation) => {
+// return operation(a, b)
+// }
+// // Method 1
+// const addition = calculate(3, 4, function(num1, num2) {
+// return num1 + num2
+// })
+// console.log(addition)
+
+// // Method 2
+// const subtraction = (a, b) => a - b
+// const subResult = calculate(10, 5, subtraction)
+// console.log(subResult)
+
+// // Method 3
+// const multiply(a, b){
+// return a * b
+// }
+
+// const multiplyResult = calculate(2, 3, multiply)
+
+// console.log(multiplyResult)
+
+
+// Pass Kar Rahe ho -> Call Nai Kar Rahe ho
+//Callback Ak Asa Function Jo Ki App Pass Kar Sakte Ho As Perameter In Another Function
+// Hera operation, function(num1, num2) {
+// return num1 + num2
+// } , subtraction, multiply Are Callback Functions
+
+// Array Callback Function -> find(), filter(), map(), forEach(), every(), some(), reduce(), reduceRight(), indexOf(), lastIndexOf(), includes(), findIndex()
+
+
+
+// function loadScript(src, callback) {
+// let script = document.createElement("script");
+// script.src = src;
+// script.onload = function() {
+// console.log("Loaded Script With SRC: " + src);
+// callback(null, src);
+// };
+// script.onerror = function() {
+// console.log("Error Loading Script With SRC: " + src);
+// callback(new Error("Src got some error"));
+// };
+// document.body.appendChild(script);
+// }
+
+
+// Handling Error
+// We can handle Error Like This By Supplying Error Argument Like This :
+// function goodmorning(error, src) {
+
+// script.onload = () => callback(null, src)
+// // script.onerror = () => callback(new Error("Src got some error"))
+// script.onerror = () => callback(new Error("Failed"))
+// }
+
+// Then Inside Of Loadscript :
+
+// loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle", function(error, src) {
+// .....
+// if(error){
+// // Handle Erroe
+// } else {
+// // Do Something
+// // Script Loaded
+// }
+// })
+
+// Another Problem Is callback(true, src); -> This Will Be Problematic To Hanlde
+// Function Ka Pura Ka Pura Control A Jata He Loadscript Likhne Vale Ke Pass
+// Ise Better Ki Me Function Likhne Vale Se Output Leke Khud Jo Chahu vo Kar Sakta Hu
+// Callback Hell Or Pyramid Of Doom
+
+// When We Have Callback Inside Callback, The Code Get Complicated. The Code Becomes Difficult To Managae.
+
+// loadScript((){
+// loadScript((){
+// loadScript((){
+// loadScript((){
+// loadScript((){
+// ....
+// ....
+// })
+// })
+// })
+// })
+// })
+
+// As Calls Become More Nested , The Code Become Deeper and Increasing More Difficult To Manage, Especially If We Have Real Code Instead Of ... -> This is Called As Pyramid Of Dom Or Callback Hell.
+
+// The Pyramid Of These CallBacks Grows Towards The Right With Every Asynchronous Action, Soon It Spreads Like Rain And Eventually Comes To The Top, Where All Work Is Done. -> Like Spiral Come Out Starting From Inside And Goes Outside.
+
+// Solution Of This Problem Is Promises.
+// A Promises Is A Promise Of Code Execution. The Code Either Executes Or Fails In Both The Cases Solution Will Be Notified
+
+// Syntax :
+// let promise = new Promise(function(resolve, reject){
+// // resolve, reject -> Predifined In Js Engin
+// // executor
+// })
+
+
+// Resolve And Reject Are Callback Provided By JS Itself
+
+// resolve(value) -> If The Job Is Finished Successfully
+// reject(error) -> If The Job Fails
+
+// The Promise Object Returned By The New Promise Constructor Has Four Properties :
+
+// 1. State -> Initially Pending, Then Changes To Fulfilled When Resolve Is Called, And Changes To Rejected When Reject Is Called.
+
+// 2. Result -> Initially Undefined, Then Changes To The Value If Resolved, Or Error If Reject -> resolve(value) -> reject(error)
+
+//consumer : Then And Catch
+// The Consumer Code Can Receive The Final Result Of A Promise Through Then And Catch
+
+// The Most fundamental Is Then:
+// promise.then(function(result){ Handler}
+// function(error){Error Handler})
+
+// If We Only Want To Know If The Promise Is Resolved Or Not We Can Use Promise.then()
+
+// If We are Interested In Successful Completion, We Can Provide Only One Function Argument To then();
+
+// let promise = new Promise(resolve => {
+// setTimeout(() => resolve("Clone"), 1000);
+// });
+// promise.then(alert); // Clone
+
+// If We Are Interested In Errors We Can Use Null As First Argument Of Than(null,f) Or We Can Use Catch
+
+// promise.catch(alert);
+// promise.finally(c)=>{}) Is Used To Perform General Cleanup
+
+// let promise = new Promise((resolve, reject) => {
+// console.log("Promise Is Pending");
+// setTimeout(() => {
+// resolve(56);
+// console.log("Promise Is Fulfilled");
+// }, 2000);
+// });
+
+// console.log(promise)
+
+// Fetch Google.com Home Page => alert("Google.com Home Page Done")
+// Fetch Data From Fetch API
+// Fetch Pictures From Server
+// Print Downloading
+// Rest Of The Script
+
+// Promise Are Used To Do Parallel Programming
+
+// Let Say 50 Promise Are There With settimeOut of 5 second -> Than All Promises Full filed In 5 second -> Not In 250 Seconds -> That Is Parelal Programming
+
+// Fulfilled -> Two Ways
+// 1. resolve(value) -> If The Job Is Finished Successfully -> fulfilled with Resolve
+// 2. reject(error) -> If The Job Fails -> Fulfilled With Reject
+
+
+
+// let p1 = new Promise((resolve, reject) => {
+// console.log("Promise is pending")
+// setTimeout(() => {
+// // console.log("I am a promise and I am resolved")
+// resolve(true)
+// }, 5000)
+// })
+
+// let p2 = new Promise((resolve, reject) => {
+// console.log("Promise is pending")
+// setTimeout(() => {
+// // console.log("I am a promise and I am rejected")
+// reject(new Error("I am an error"))
+// }, 5000)
+// })
+
+// // To get the value
+// p1.then((value) => {
+// console.log(value)
+// })
+
+// // To catch the errors
+// p2.catch((error) => {
+// console.log("some error occurred in p2")
+// })
+// // Error Saw Not Saw In Console -> We Catched Arror
+
+// p2.then((value) => {
+// console.log(value)
+// }, (error) => {
+// console.log(error)
+// })
+// p2.than(resolve,reject) // Syntax
+
+
+// Promise Chaining
+
+// We Can Chain Promises And Make Sure That The Result Of A Promise Passes To Another Promise
+
+// Here Is The Flow Of Execution
+// 1. The initial promise resolves in 1 Second (Assumption)
+// 2. The next .then() handler is then called Which returns a new promise (Resolved With 2 Values)
+// 3. The next .then() gets the result of previous one and this is resolved to a new promise amd This Is Going On And On
+
+
+// Every call To .then() Returns A New Promise Whose Value Is Passed To The Next One And So On . We Can Even Create Custom Promise Inside .then()
+
+
+// let p1 = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// console.log("Resolved after 2 seconds")
+// resolve(56)
+// }, 2000)
+// })
+
+// p1.then((value) => {
+// console.log(value)
+// return new Promise((resolve, reject) => {
+// setTimeout(() => { resolve("Promise 2") }, 2000)
+// })
+// }).then((value) => {
+// console.log("We are done")
+// return 2
+// }).then((value)=>{
+// console.log("Now we are pakka done")
+// })
+
+
+// LoadScript Function With Promises
+// const loadScript = (src) => {
+// return new Promise((resolve, reject) => {
+// let script = document.createElement("script");
+// script.type = "text/javascript";
+// script.src = src;
+// document.body.appendChild(script);
+
+// script.onload = () => {
+// resolve("Script has been loaded successfully");
+// };
+
+// script.onerror = () => {
+// reject(new Error(`Failed to load script: ${src}`));
+// };
+// });
+// };
+
+// Load the script and chain the promises
+
+// let p1 = loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js");
+
+// p1.then((value) => {
+// console.log(value);
+// // Loading another script after the first one is loaded
+// return loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js");
+// }).then((value) => {
+// console.log(value);
+// // You can continue chaining more scripts if needed
+// }).catch((error) => {
+// console.error("Script loading failed:", error);
+// });
+
+// Attaching Multiple Handler To A Promise
+
+// Promise Chaining -> Run One By One
+// Lets Say 10 Promise Chain Each Has SetTimeOut Of 5 Second -> Than Run In 50 Second
+// Ak Ki Promise Ki value A Jane Par Dusri Promise -> Dusri Ki Value A Jane Par Tesri -> Tesri Ki Value A Jane Par Chauthi -> So and So
+// Like We Are Passing One Promise Value In Second And Second Promise Value Passed On Third And So And So -> Promise Chaining
+// Lets Say In 10 Promise Chaining Error Occurred At 5th Promise Vo Directly Next Vala Catch Pakad Lega Other Promise Ko Skip Karke
+
+// Multiple Handler In Promise -> Run Independent
+// Lets Say 10 Promise Chain Each Has SetTimeOut Of 5 Second -> Than Run In 5 Second
+
+
+// Let p Is Promise
+// p.then(handler1)
+// p.then(handler2)
+// p.then(handler3)
+// All Run Independently
+
+
+ // let promise = new Promise((resolve) => setTimeout(() => resolve("Done"), 5000));
+
+ // promise.then((value) => {
+ // console.log("Handler 1: " + value);
+ // });
+
+ // promise.then((value) => {
+ // console.log("Handler 2: " + value);
+ // });
+
+// Promise API
+
+
+// let p1 = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve("Value 1");
+// }, 11000);
+// });
+
+// let p2 = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// // resolve("Value 2");
+// reject(new Error("Error"));
+// }, 2000);
+// });
+
+// let p3 = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve("Value 3");
+// }, 3000);
+// });
+
+// p1.then((value) => {
+// console.log(value)
+// })
+
+// p2.then((value) => {
+// console.log(value)
+// })
+
+// p3.then((value) => {
+// console.log(value)
+// })
+
+// let promise_all = Promise.all([p1, p2, p3])
+// let promise_all = Promise.allSettled([p1, p2, p3])
+// let promise_all = Promise.race([p1, p2, p3])
+// let promise_all = Promise.resolve(6)
+// let promise_all = Promise.reject(new Error("Hey"))
+// promise_all.then((value) => {
+// console.log(value)
+// })
+
+// There Are 6 Static Methods Of Promise Class
+// 1. Promise.all(promises) -> Waits For All Promises To Resolves And Returns Their Result In An Array If Any One Of The Promise Rejects, It becomes Immediately Rejected If Any One Of That Fails, Its Become Error & All Other Result Are Ignored
+
+// 2. Promise.allSettled(promises) -> Waits For All Promises To Settle And Returns Their Result As An Array Of Objects With Status And Value.
+
+// 3. Promise.race(promises) -> Waits For The First Promise To Settle And Its Result/Error Become The Output -> Jo Bhi Sabse Pahle Fulfilled Hogi Uski Value Mil Javegi
+
+// 4. Promise.any(promises) -> Waits For The First Promise To Settle And Its Result Become Outcome. Throws Aggregate Error If All The Promises Are Rejected.
+// Jo Bhi Sabse Pahle Resolve Hogi Uski Value Mil Javegi
+
+// 5. Promise.resolve(value) -> Makes A Resolved Promise With The Given Value
+
+// 6. Promise.reject(error) -> Makes A Rejected Promise With The Given Error
+
+
+// Async / Await
+// There Is A Special Syntax To Work With Promises In A More Easier Way
+
+// A Function Can Be Declared With Async Keyword -> It Returns A Promise
+
+// A Function Can Be Made Async By Using Async Keyword -> It Returns A Promise
+// async function harry(){
+// Code Here
+// }
+
+// Ham Kisi Bhi Function Ko Async Bana Sakte Hai -> async Keyword Lagana Padta Hai Or Uske Baad Uske Andar Promise Ko Awake Kar Sakte he
+
+// An Async Function Always Return A Promise. Other Values Are Wrapped Into It Automatically As Promises
+
+// We Can Do Something Like This
+// harry().then(alert)
+
+// So Async Ensure That The Function Returns A Promise And Wraps Non-Promises In It Automatically
+
+// Method 1:
+// async function harry() {
+// let delhiWeather = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve("27°C");
+// }, 1000);
+// });
+
+// let bangaloreWeather = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve("21°C");
+// }, 7000);
+// });
+
+// // Handling the weather data using 'then'
+// delhiWeather.then((temperature) => {
+// alert(`Delhi Weather: ${temperature}`);
+// });
+
+// bangaloreWeather.then((temperature) => {
+// alert(`Bangalore Weather: ${temperature}`);
+// });
+
+// // Using 'await' keyword to wait for the promises to resolve
+// console.log("Fetching Delhi Weather Please Wait...");
+// let delhiW = await delhiWeather;
+// // await Keyword Stops The Execution Of The Function Until The Promise Is Resolved
+// console.log("Fetching Bangalore Weather Please Wait...");
+// let bangaloreW = await bangaloreWeather;
+// // Returning the values of the resolved promises
+// return [delhiW, bangaloreW];
+
+// console.log("Welcome to the weather control room");
+// }
+
+// let a = harry();
+// // let a = harry(); let b = charry(); -> Excute Parallely
+// console.log(a); // Return Promise
+// // Good Practice
+
+// a.then((value) => {
+// console.log(value);
+// })
+
+
+// // Call the function
+// harry();
+
+
+
+// async function harry() {
+// let delhiWeather = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve("27 Deg")
+// }, 2000)
+// })
+
+// let bangaloreWeather = new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve("21 Deg")
+// }, 5000)
+// })
+
+// harry().then((x)) =>{
+// alert(x)
+// }
+
+// // delhiWeather.then(alert)
+// // bangaloreWeather.then(alert)
+// console.log("Fetching Delhi Weather Please wait ...")
+// let delhiW = await delhiWeather
+// console.log("Fetched Delhi Weather: " + delhiW)
+// console.log("Fetching Bangalore Weather Please wait ...")
+// let bangaloreW = await bangaloreWeather
+// console.log("Fetched Bangalore Weather: " + bangaloreW)
+// return [delhiW, bangaloreW]
+// }
+
+// const cherry = async () => {
+// console.log("Hey I am cherry and I am waiting ")
+// }
+
+// const main1 = async () => {
+// console.log("Welcome to weather control room")
+// let a = await harry()
+// let b = await cherry()
+
+// }
+// main1()
+
+
+// The Await Keyword
+// There Is Another Keyword Called Await That Works Only With Inside An Async Function
+
+// let value = await promise;
+// Promises Ki value value Me A jayegi
+
+// The Await Keyword Makes JavaScript Wait Until The Promise Settles And Returns Its Value.
+
+// It Just More Elegant Syntax Of Getting The Promise Result Than Using .then() And .catch() Plus It Easier To Read And Write
+
+
+// Error Handling
+
+// We All Make Mistakes In Our Codes. Also Sometimes Our Script Can Have Error In It. Usually Program Halt When Error Occurs.
+
+// The Try And Catch Syntax Allow Us To Catch The Error So That Our Script Instead Of Dying Can Do Something More Relevant.
+
+// The Try And Catch Syntax
+// It Has Two Main Blocks
+// 1. try
+// 2. catch
+// When Error Come Out Program Doesn't Stop It Just Continues
+
+// try{
+// // Try Code Goes Here
+// } catch(error){
+// // Catch Code Goes Here
+// // The Error Variable Contain An Error Object
+// }
+
+// setTimeout(()=>{
+// console.log("Hacking wifi.... Please wait..." )
+// }, 1000)
+
+// try{
+// console.log(rahul)
+// }
+// catch(err){
+// console.log("Balle balle")
+// }
+
+
+// setTimeout(()=>{
+// console.log("Fetching username and password.... Please wait..." )
+// }, 2000)
+
+// setTimeout(()=>{
+// console.log("Hacking Rahul's facebook id.... Please wait..." )
+// }, 3000)
+
+// setTimeout(()=>{
+// console.log("Username and password of Rahul (+919356700001) fetched.... Please wait..." )
+// }, 4000)
+
+// It Work Like This
+// 1. First Code In try Will Excuted
+// 2. If There Is No Error In try Then Catch Is Ignored Else Catch Is Excuted
+
+// Try Catch Work Synchrounously
+// If An Exception Happen In Sheduled Code (e.g setTimeout) , Than Try Catch Wont Catch It: -> In Short Script Die And Wont Work More
+// When Error Come -> Excution Will Stop And Catch Will Not Work
+
+// Ye Handle Nai Hoga
+
+// try{
+// setTimeout(()=>{
+// console.log(rahul)
+// }, 100)
+// }
+// catch(err){
+// console.log("Balle balle")
+// }
+
+// Ye Handle Hoga
+
+// try{
+// setTimeout(()=>{
+// try{
+// console.log(rahul)
+// } catch(error){
+// console.log("Balle balle Error Catched ")
+// }
+// }, 100)
+// }
+// catch(err){
+// console.log("Balle balle")
+// }
+
+// The Error Object
+
+// For All Built In Error There Is A Predefined Error Object Has Two Main Property
+// 1. name
+// 2. message
+
+// we Can Use .stack To Get The Stack Trace Of The Error
+// Syntax:
+// try{
+// hey ; // Invalid And Through Error -> Variable Is Not Defined
+// } catch(error){
+// console.log(error.name)
+// console.log(error.message)
+// console.log(error.stack)
+// }
+
+// Throwing Custom Error
+
+// We Can Throw Custom Error By Using The Throw Syntax
+
+// Syntax:
+
+// if(age>180){
+// throw new Error("This Is Probably Not True")
+// }
+
+// We Can Also Throw A Particular Error By Using Built In Constructor For Standard Error:
+// let error = new SyntaxError("This Is An Error")
+// let error = new ReferenceError("This Is An Error")
+
+// try {
+// let age = prompt("Enter your age")
+// age = Number.parseInt(age)
+// if(age>150){
+// throw new ReferenceError("This is probably not true") // Custom New Error
+// }
+// } catch (error) {
+// console.log(error.name)
+// console.log(error.message)
+// console.log(error.stack)
+// }
+
+// console.log("The script is still running")
+
+// All Error List :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors
+
+// Finally Clause
+
+// The Try Catch construct may have one more code clause : finally
+// If it exists it runs in all cases:
+// after try if there were no errors, and
+// after catch if there were errors
+
+// if There Is Return in Try, Finally Is Executed Just Before The Function Returns Or Just Before Control Return To The Outer Code
+
+// const f = () => {
+// try {
+// let a = 0;
+// // console.log(program)
+// console.log("Program ran successfully")
+// return
+// }
+// catch (err) {
+// console.log("This is an error")
+// console.log(p)
+// }
+// finally {
+// console.log("I am a good boy")
+// // Close the file
+// // Exit the Loop
+// // Write to the log file
+// }
+// }
+
+// f()
+// console.log("End")
+
+
+// Promise are Way Of Asynchronous Programming Ka
+// Practice Set
+// Q1 Write A Program to load a javascript file in a browser using promises. Use .then() to display an alert when the load is complete.
+
+
+const loadScript = async (src) => {
+ return new Promise((resolve, reject) => {
+ let script = document.createElement("script")
+ script.src = src
+ script.onload = () => {
+ resolve(src + " Done success")
+ }
+ document.head.append(script)
+ })
+}
+// Problem number 1
+// let a = loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js")
+// a.then((value) => {
+// console.log(value)
+// })
+
+// Q2 Write The Same Program From Previous Question And Use async/await syntax
+
+// Problem number 2
+// const main2 = async () => {
+// console.log(new Date().getMilliseconds())
+// let a = await loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js")
+// console.log(a)
+// console.log(new Date().getMilliseconds())
+// }
+// main2()
+
+// Q3 Create A Promise Which Rejects After 3 Seconds Use An Async/Await To Get Its Value. Use A Try Catch To Handle Its Error
+
+// Problem number 3
+// let p = () => {
+// return new Promise((resolve, reject) => {
+// setTimeout(() => {
+// reject(new Error("Please this is not acceptable"))
+// }, 3000)
+// })
+// }
+
+// let a = async () => {
+// try {
+// let c = await p()
+// console.log(c)
+// }
+// catch (err) {
+// console.log("This error has been handled")
+// }
+// }
+// a()
+
+// Q4 Write A Program Using Promise.all() Inside An Async/Await To Await 3 Promises. Compare Its Results With The Case Where We Await Them One By One
+// Problem number 4
+
+// let p1 = async () => {
+// return new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve(10)
+// }, 2000)
+// })
+// }
+// let p2 = async () => {
+// return new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve(20)
+// }, 1000)
+// })
+// }
+// let p3 = async () => {
+// return new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve(30)
+// }, 3000)
+// })
+// }
+
+// const run = async () => {
+// console.time("run")
+// // let a1 = await p1() // Fetch first 10 products from the database
+// // let a2 = await p2() // Fetch another 10 products from the database
+// // let a3 = await p3() // Fetch yet another 10 products from the database
+
+// // Better Way -> Optimization
+// let a1 = p1() // Fetch first 10 products from the database
+// let a2 = p2() // Fetch another 10 products from the database
+// let a3 = p3() // Fetch yet another 10 products from the database
+// let a1a2a3 = await Promise.all([a1, a2, a3])
+// console.log(a1a2a3)
+// // console.log(a1, a2, a3)
+// console.timeEnd("run")
+// }
+
+// run()
+
diff --git a/Ch-10-Network-Request-And-Storing-Data.zip b/Ch-10-Network-Request-And-Storing-Data.zip
new file mode 100644
index 0000000..0a038eb
Binary files /dev/null and b/Ch-10-Network-Request-And-Storing-Data.zip differ
diff --git a/Ch-10-Network-Request-And-Storing-Data/.gitignore b/Ch-10-Network-Request-And-Storing-Data/.gitignore
new file mode 100644
index 0000000..40b878d
--- /dev/null
+++ b/Ch-10-Network-Request-And-Storing-Data/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Ch-10-Network-Request-And-Storing-Data/Readme.md b/Ch-10-Network-Request-And-Storing-Data/Readme.md
new file mode 100644
index 0000000..8e4335e
--- /dev/null
+++ b/Ch-10-Network-Request-And-Storing-Data/Readme.md
@@ -0,0 +1,455 @@
+This JavaScript code consists of three asynchronous functions: `createTodo`, `getTodo`, and `mainFunc`. These functions interact with a placeholder API (`jsonplaceholder.typicode.com`) that simulates a RESTful backend for testing and prototyping.
+
+### 1. `createTodo` Function
+```javascript
+const createTodo = async (todo) => {
+ let options = {
+ method: "POST",
+ headers: {
+ "Content-type": "application/json"
+ },
+ body: JSON.stringify(todo),
+ }
+ let p = await fetch('https://jsonplaceholder.typicode.com/posts', options)
+ let response = await p.json()
+ return response
+}
+```
+- **Purpose:** This function creates a new "to-do" item by sending a POST request to the API.
+- **Parameters:** It takes a `todo` object as input, which includes properties like `title`, `body`, and `userId`.
+- **Options Object:**
+ - `method: "POST"` specifies that this is a POST request.
+ - `headers: { "Content-type": "application/json" }` sets the content type to JSON, meaning the server expects JSON-formatted data.
+ - `body: JSON.stringify(todo)` converts the `todo` object into a JSON string to be sent in the request body.
+- **Fetch Request:**
+ - The `fetch` function sends the POST request to `'https://jsonplaceholder.typicode.com/posts'` with the specified options.
+ - The `await` keyword ensures that the function waits for the response before moving on.
+- **Response Handling:**
+ - `let response = await p.json()` converts the response from the server to a JavaScript object.
+ - The function then returns this `response` object.
+
+### 2. `getTodo` Function
+```javascript
+const getTodo = async (id) => {
+ let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id)
+ let r = await response.json()
+ return r
+}
+```
+- **Purpose:** This function retrieves a specific "to-do" item by its ID.
+- **Parameters:** It takes an `id` as input, which is the identifier for the to-do item.
+- **Fetch Request:**
+ - The `fetch` function sends a GET request to `'https://jsonplaceholder.typicode.com/posts/' + id`, where `id` is appended to the URL to specify which item to retrieve.
+ - `let response = await fetch(...)` waits for the response from the server.
+- **Response Handling:**
+ - `let r = await response.json()` converts the response data to a JavaScript object.
+ - The function returns this object, which contains the details of the requested to-do item.
+
+### 3. `mainFunc` Function
+```javascript
+const mainFunc = async () => {
+ let todo = {
+ title: 'Harry2',
+ body: 'bhai2',
+ userId: 1100,
+ }
+ let todor = await createTodo(todo)
+ console.log(todor)
+ console.log(await getTodo(101))
+}
+```
+- **Purpose:** This is the main function that orchestrates the execution of the `createTodo` and `getTodo` functions.
+- **Todo Object:**
+ - It defines a `todo` object with a `title`, `body`, and `userId`.
+- **Creating a To-Do:**
+ - `let todor = await createTodo(todo)` creates a new to-do using the `createTodo` function and waits for the result.
+ - `console.log(todor)` prints the response from the `createTodo` function, showing the details of the newly created to-do item.
+- **Fetching a To-Do:**
+ - `console.log(await getTodo(101))` fetches and prints the to-do item with ID `101` using the `getTodo` function.
+
+### 4. Execution
+```javascript
+mainFunc()
+```
+- The `mainFunc` function is called, initiating the process of creating and fetching to-do items.
+
+### Summary
+- **createTodo:** Sends a POST request to create a new to-do item.
+- **getTodo:** Sends a GET request to retrieve a specific to-do item by ID.
+- **mainFunc:** Demonstrates creating a to-do item and then fetching an existing one, printing both to the console.
+
+
+**Synchronous** and **asynchronous** programming are two different approaches to handling tasks and operations in a program, particularly when dealing with I/O operations (like reading files, making network requests, or accessing databases) or any tasks that may take some time to complete. Here's a comparison of the two:
+
+### Synchronous Programming
+
+**1. Execution Flow:**
+ - In synchronous programming, tasks are executed one after the other, in a sequential order.
+ - Each task waits for the previous one to complete before starting.
+ - If a task takes a long time (e.g., reading a large file), the program will pause and wait until the task is finished before moving on to the next one.
+
+**2. Blocking Behavior:**
+ - Synchronous code is typically **blocking**. This means that when a task is being executed, the entire program might stop and wait for that task to complete before it can continue executing the next line of code.
+ - Example:
+ ```javascript
+ function getData() {
+ // Simulate a long-running task
+ let data = readFileSync('data.txt'); // This will block until the file is read
+ console.log(data);
+ }
+ console.log('Before getData');
+ getData();
+ console.log('After getData'); // This will run only after getData finishes
+ ```
+
+**3. Simplicity:**
+ - Synchronous programming is often simpler to write and reason about because the flow of control is straightforward.
+
+**4. Performance:**
+ - Synchronous code can lead to performance bottlenecks, especially in situations where multiple tasks need to be performed concurrently. If a program is waiting on a slow operation, the entire program can become unresponsive.
+
+### Asynchronous Programming
+
+**1. Execution Flow:**
+ - In asynchronous programming, tasks are executed independently of the main program flow.
+ - When an asynchronous task is initiated, the program does not wait for it to complete. Instead, it moves on to execute the next task.
+ - Once the asynchronous task is complete, the program is notified (usually through callbacks, promises, or async/await), and any associated code is then executed.
+
+**2. Non-Blocking Behavior:**
+ - Asynchronous code is typically **non-blocking**. The program continues executing other tasks while waiting for the asynchronous operation to complete.
+ - Example:
+ ```javascript
+ async function getData() {
+ let data = await readFile('data.txt'); // This will not block other operations
+ console.log(data);
+ }
+ console.log('Before getData');
+ getData(); // getData is initiated, but the program doesn't wait for it to finish
+ console.log('After getData'); // This runs immediately after getData is called
+ ```
+
+**3. Complexity:**
+ - Asynchronous programming can be more complex, especially when dealing with multiple tasks that depend on each other. This can lead to "callback hell" or make it harder to follow the program's logic.
+
+**4. Performance:**
+ - Asynchronous code can greatly improve performance, especially in I/O-bound or highly concurrent applications, by allowing multiple tasks to run concurrently without blocking the main program.
+
+### Key Differences
+
+| Aspect | Synchronous Programming | Asynchronous Programming |
+|-----------------------|----------------------------------------|-----------------------------------|
+| Execution | Sequential, one task at a time | Concurrent, multiple tasks can run simultaneously |
+| Blocking Behavior | Blocking | Non-blocking |
+| Complexity | Simpler and easier to understand | More complex, harder to manage |
+| Performance | Can cause bottlenecks | Improves performance in I/O-bound tasks |
+| Use Case | Suitable for simple, linear tasks | Suitable for I/O-bound, time-consuming tasks, and concurrency |
+
+### When to Use Each
+
+- **Synchronous Programming:**
+ - Use when tasks are simple, quick, and need to be executed in a strict sequence.
+ - Ideal for CPU-bound tasks where tasks don’t involve waiting on external resources like network or file I/O.
+
+- **Asynchronous Programming:**
+ - Use when tasks involve I/O operations, such as network requests, reading files, or databases, especially when you need the program to remain responsive.
+ - Ideal for scenarios where you want to handle multiple operations at the same time without blocking the main thread of execution.
+
+
+In JavaScript, particularly when dealing with web development and making HTTP requests, there are several methods (also called HTTP methods) that are commonly used. These methods define the type of action that should be performed on a given resource (like a web page or API endpoint). Here’s an overview of the main HTTP methods and how they work in JavaScript:
+
+### 1. **GET**
+ - **Purpose:** Retrieve data from a server.
+ - **Usage:** Used to request data from a specified resource, like fetching a web page or getting data from an API.
+ - **Characteristics:**
+ - Typically doesn’t alter the state of the server.
+ - Parameters are often passed in the URL as query strings.
+ - Safe and idempotent, meaning repeated requests should have the same effect as a single request.
+ - **Example:**
+ ```javascript
+ fetch('https://jsonplaceholder.typicode.com/posts/1')
+ .then(response => response.json())
+ .then(data => console.log(data))
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 2. **POST**
+ - **Purpose:** Send data to the server to create a new resource.
+ - **Usage:** Commonly used for submitting form data or creating a new entry in a database.
+ - **Characteristics:**
+ - The request body contains the data to be sent to the server.
+ - It’s not idempotent; multiple requests can result in different outcomes.
+ - **Example:**
+ ```javascript
+ const newPost = {
+ title: 'New Post',
+ body: 'This is the body of the new post.',
+ userId: 1
+ };
+
+ fetch('https://jsonplaceholder.typicode.com/posts', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(newPost)
+ })
+ .then(response => response.json())
+ .then(data => console.log(data))
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 3. **PUT**
+ - **Purpose:** Update an existing resource entirely.
+ - **Usage:** Used to update the data of a specific resource, typically replacing it with new data.
+ - **Characteristics:**
+ - The entire resource is updated with the data provided in the request.
+ - Idempotent, meaning multiple identical requests should have the same effect as a single one.
+ - **Example:**
+ ```javascript
+ const updatedPost = {
+ title: 'Updated Post',
+ body: 'This is the updated body of the post.',
+ userId: 1
+ };
+
+ fetch('https://jsonplaceholder.typicode.com/posts/1', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(updatedPost)
+ })
+ .then(response => response.json())
+ .then(data => console.log(data))
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 4. **PATCH**
+ - **Purpose:** Partially update an existing resource.
+ - **Usage:** Used when you want to update only certain fields of a resource, rather than replacing the entire resource like with `PUT`.
+ - **Characteristics:**
+ - Only the fields provided in the request are updated.
+ - Idempotent, like `PUT`.
+ - **Example:**
+ ```javascript
+ const partialUpdate = {
+ title: 'Partially Updated Title'
+ };
+
+ fetch('https://jsonplaceholder.typicode.com/posts/1', {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(partialUpdate)
+ })
+ .then(response => response.json())
+ .then(data => console.log(data))
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 5. **DELETE**
+ - **Purpose:** Delete a specified resource.
+ - **Usage:** Used to remove a resource from the server.
+ - **Characteristics:**
+ - This action removes the specified resource from the server.
+ - Idempotent, meaning multiple identical requests should have the same effect as a single one.
+ - **Example:**
+ ```javascript
+ fetch('https://jsonplaceholder.typicode.com/posts/1', {
+ method: 'DELETE'
+ })
+ .then(response => {
+ if (response.ok) {
+ console.log('Post deleted');
+ }
+ })
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 6. **OPTIONS**
+ - **Purpose:** Describe the communication options for the target resource.
+ - **Usage:** Often used in CORS (Cross-Origin Resource Sharing) scenarios to determine what HTTP methods and headers are allowed by the server.
+ - **Characteristics:**
+ - Does not change the state of the resource.
+ - Often used by browsers automatically before a request is made.
+ - **Example:**
+ ```javascript
+ fetch('https://jsonplaceholder.typicode.com/posts', {
+ method: 'OPTIONS'
+ })
+ .then(response => {
+ console.log(response.headers.get('Allow'));
+ })
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 7. **HEAD**
+ - **Purpose:** Retrieve the headers of a resource, without the body.
+ - **Usage:** Used when you want to check the headers (like content type, content length) before fetching the resource.
+ - **Characteristics:**
+ - Similar to `GET`, but the response does not contain the body.
+ - Useful for checking what a `GET` request will return without actually retrieving the data.
+ - **Example:**
+ ```javascript
+ fetch('https://jsonplaceholder.typicode.com/posts/1', {
+ method: 'HEAD'
+ })
+ .then(response => {
+ console.log(response.headers.get('Content-Type'));
+ })
+ .catch(error => console.error('Error:', error));
+ ```
+
+### 8. **TRACE**
+ - **Purpose:** Echoes the received request so that a client can see what changes or additions might have been made by intermediate servers.
+ - **Usage:** Rarely used in practice; primarily used for diagnostic purposes to trace the path a request takes to reach the server.
+ - **Characteristics:**
+ - The server responds with the exact request it received.
+ - Can expose information about the path taken to the server.
+ - **Note:** For security reasons, many servers disable or reject `TRACE` requests.
+
+### 9. **CONNECT**
+ - **Purpose:** Establishes a tunnel to the server identified by the target resource.
+ - **Usage:** Typically used with proxies that can dynamically switch to being a tunnel (e.g., SSL tunneling).
+ - **Characteristics:**
+ - Opens a TCP connection for tunneling, typically for SSL encryption.
+ - Used in HTTP proxies to create an encrypted tunnel to the destination server.
+
+These methods are part of the HTTP protocol and are crucial for building and interacting with RESTful APIs in JavaScript. The most commonly used methods are `GET`, `POST`, `PUT`, `PATCH`, and `DELETE`, as they cover the core CRUD (Create, Read, Update, Delete) operations needed for most web applications.
+
+### Local Storage
+
+
+
+
+# Practice Set
+
+### Q1: Use a Free API From The Internet And Feed Your App With Live Data
+
+You've already done this by fetching data from the "kontests.net" API and displaying it on the page. Here’s a quick explanation:
+
+- **Fetching Data**:
+ ```javascript
+ let response = fetch(url)
+ ```
+ You use the `fetch` API to get data from the specified URL. This returns a promise that resolves to the response object.
+
+- **Handling JSON**:
+ ```javascript
+ response.then((v) => {
+ return v.json()
+ })
+ ```
+ Once the data is fetched, you convert it to JSON format, which is a structured format to represent data.
+
+- **Displaying Data**:
+ ```javascript
+ for (item in contests) {
+ // Creating HTML dynamically
+ ihtml += `
+
+
+
+
${contests[item].name}
+
Status is ${contests[item].status} and site is ${contests[item].site}
+
In 24 Hours? ${contests[item].in_24_hours}
+
Starts at: ${contests[item].start_time}
+
Ends at: ${contests[item].end_time}
+
Visit Contest
+
+
+ `;
+ }
+ cardContainer.innerHTML = ihtml;
+ ```
+ You loop through the contests, create HTML for each contest, and inject it into the page.
+
+### Q2: Create A Note-Saving App Which Stores Your Note To localStorage
+
+You’ve implemented the storage part where the note is saved to `localStorage`:
+
+- **Prompting for a Note**:
+ ```javascript
+ let a = prompt("Enter your note")
+ if (a) {
+ localStorage.setItem("note", a)
+ }
+ ```
+ The app prompts the user to enter a note, which is then saved in the `localStorage` under the key `"note"`.
+
+### Q3: Repeat Q2 And Fetch The Note Which User Entered In The Previous Question
+
+You’ve also implemented fetching the note:
+
+- **Retrieving the Note**:
+ ```javascript
+ let n = localStorage.getItem("note")
+ alert("Your note is " + n)
+ ```
+ The note stored in `localStorage` is fetched using `getItem` and displayed using an alert.
+
+### Q4: Delete The Note In The Previous Question
+
+Finally, you’ve implemented the deletion of the note:
+
+- **Confirm and Delete**:
+ ```javascript
+ let c = confirm("Do you want to delete your note?")
+ if (c) {
+ localStorage.removeItem("note")
+ alert("Note deleted successfully!")
+ }
+ ```
+ The app asks for confirmation from the user, and if confirmed, it deletes the note using `removeItem` and alerts the user that the note has been deleted.
+
+### Complete Code Integration:
+
+```javascript
+// Q1: Fetch and display contests data
+let url = "https://kontests.net/api/v1/all";
+let response = fetch(url);
+response.then((v) => {
+ return v.json();
+}).then((contests) => {
+ console.log(contests);
+ let ihtml = "";
+ for (let item in contests) {
+ console.log(contests[item]);
+ ihtml += `
+
+
+
+
${contests[item].name}
+
Status is ${contests[item].status} and site is ${contests[item].site}
+
In 24 Hours? ${contests[item].in_24_hours}
+
Starts at: ${contests[item].start_time}
+
Ends at: ${contests[item].end_time}
+
Visit Contest
+
+
+ `;
+ }
+ cardContainer.innerHTML = ihtml;
+});
+
+/* ******************* NOTES APP (REMAINING QUESTIONS OF PRACTICE SET) *********** */
+
+// Q2: Save a note to localStorage
+let n = localStorage.getItem("note");
+alert("Your note is " + n);
+
+let a = prompt("Enter your note");
+if (a) {
+ localStorage.setItem("note", a);
+}
+
+// Q3: Fetch the saved note (covered in the alert above with Q2)
+
+// Q4: Delete the note
+let c = confirm("Do you want to delete your note?");
+if (c) {
+ localStorage.removeItem("note");
+ alert("Note deleted successfully!");
+}
+```
diff --git a/Ch-10-Network-Request-And-Storing-Data/image.png b/Ch-10-Network-Request-And-Storing-Data/image.png
new file mode 100644
index 0000000..d667e2f
Binary files /dev/null and b/Ch-10-Network-Request-And-Storing-Data/image.png differ
diff --git a/Ch-10-Network-Request-And-Storing-Data/index.html b/Ch-10-Network-Request-And-Storing-Data/index.html
new file mode 100644
index 0000000..2488b41
--- /dev/null
+++ b/Ch-10-Network-Request-And-Storing-Data/index.html
@@ -0,0 +1,78 @@
+
+
+
+
+
+
+ replit
+
+
+
+
+
+
+
+ Contests
+
+
+
+
+
+
+
+
+
+
Programming Contests
+
This is a simple hero unit, a simple jumbotron-style component for calling extra
+ attention to featured content or information.
+
+
It uses utility classes for typography and spacing to space content out within the larger
+ container.
+
Learn more
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Ch-10-Network-Request-And-Storing-Data/script.js b/Ch-10-Network-Request-And-Storing-Data/script.js
new file mode 100644
index 0000000..12dbaa1
--- /dev/null
+++ b/Ch-10-Network-Request-And-Storing-Data/script.js
@@ -0,0 +1,291 @@
+// Fetch API
+// The Fetch API provides a simple way to fetch resources (for example images, documents, or streams) over the internet
+
+// JavaScript Can Be Used To Send And Retrieve Information From The Network When Needed (AJAX)
+
+// AJAX Used Earlier -> Now JSON Is Widely Used
+
+// AJAX -> Asynchronous JavaScript And XML
+
+// Fetch API
+
+// Fetch Is Used To Get Data Over The Internet
+
+// let promise = fetch(URL, [options])
+// Without Option A GET Request Is Sent
+
+// Getting The Response Is A 2-Stage Process
+
+// 1. An Object Of Response Class Containing "Status" And "Ok" Properties
+// Status - The HTTP Status Code, eg 200
+// Ok - Boolean, True If The HTTP Status Code Is 200-299
+
+// 2. After That We Need To Call Another Method To Access The Body In Different Formats
+
+// Response.text() - Read The Response As Text
+// Response.json() - Parse The Response As JSON
+
+// Other Methods Include - Response.formData(), Response.blob(), Response.arrayBuffer()
+
+// Note - We Can Use Only One Body Method. For Example If We Have Used Response.text() Then We Cannot Use Response.json()
+
+// Response Headers
+
+// The Response Headers Are Available In Response.headers
+
+// Request Headers
+// To Set A Request Header In Fetch, We Can Use The Headers Option
+
+// let res = fetch(url, {
+// header: {
+// Authentication: 'Secret'
+// }
+// });
+
+
+// POST Request
+
+// let p = fetch("https://api.rainviewer.com/public/weather-maps.json")
+// p.then((response) => {
+// console.log(response.status)
+// console.log(response.ok)
+// console.log(response.headers)
+// return response.json()
+// }).then(data => {
+// console.log(data)
+// })
+// Why Two .then Is Mentioned Above?
+// Response Contain Two Properties - Status And Ok
+// Data Is The Actual Result Of The Request
+
+// POST Request
+// To Make Post Request, We Need To Use Fetch Options
+// Method -> HTTP Method, E.g POST
+// Body -> The Request Body
+
+// const createTodo = async (todo) => {
+// let options = {
+// method: "POST",
+// headers: {
+// "Content-type": "application/json"
+// },
+// body: JSON.stringify(todo),
+// }
+// let p = await fetch('https://jsonplaceholder.typicode.com/posts', options)
+// let response = await p.json()
+// return response
+// }
+
+// const getTodo = async (id) => {
+// let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id)
+// let r = await response.json()
+// return r
+// }
+
+// const mainFunc = async () => {
+// let todo = {
+// title: 'Harry2',
+// body: 'bhai2',
+// userId: 1100,
+// }
+// let todor = await createTodo(todo)
+// console.log(todor)
+// console.log(await getTodo(101))
+// }
+
+// mainFunc()
+
+// let response = await fetch('/url', {
+// method: 'POST',
+// headers: {
+// 'Content-Type': 'application/json'
+// },
+// body: JSON.stringify({
+// title: 'foo',
+// body: 'bar',
+// userId: 1,
+// })
+// })
+
+// let result = await response.json()
+
+// JavaScript Cookies
+// Cookies Are Small Strings Of Data Stored By The Client Side Stored In Browser
+// In JavaScript, Document.cookie Property Can Be Used To Access Cookies
+
+// Cookies Are Set By Web Server Using Set-Cookie HTTP Header. Next Time When The Request Is Sent To The Same Domain, The Browser Sends The Cookie Using Cookie HTTP Header In The Request. That Way The Server Knows Who Sent The Request.
+
+// We Can Also Access Cookies Using document.cookie Property
+// alert(document.cookie) -> Contain Key Value Pairs Decoded
+
+// Key Value Pair Are Separated By Delimited By ; -> Key = Pair;
+
+// Writing A Cookie
+// An Assignment To Document.cookie Is Treated Specially In A Way That Write Operation Doesn't Touch Other Cookie
+
+// document.cookie = "name=harry1122334400"
+// Updates Only Cookie Named User To Harry
+
+// Bahot Chota Sa Data Store Karneka Tarika
+// console.log(document.cookie)
+// document.cookie = "name=harry1122334400"
+// document.cookie = "name2=harry11223344002" // Set Call
+// document.cookie = "name=harry" // Old Is Updated
+// let key = prompt("enter your key")
+// let value = prompt("enter your value")
+// document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
+// console.log(document.cookie)
+
+// Encode URI Component -> This Function Encodes A Set Of Special Characters In A Way That The Component Can Be Decoded Using DecodeURI
+
+// This Function Helps Keep The Valid Formatting. It Is Used Like This
+
+// document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
+
+// This Way Spacial Character Are Encoded
+
+// Cookies Option
+
+// Cookies Have Several Options Which Can Be Provided After Key=Value To A Set Call Like This :
+
+// document.cookie = "user=harry;path=/a;expires=Tue,29 March 204"
+// path -> Which Domain The Cookie Will Be Available On
+// document.cookie = "user=harry;path=/a;expires=Tue,29 March 2041 12:00:33 GMT"
+// Set Only One Cookies With Path And Expires
+// document.cookies -> Can Set Only One Cookie At A Time Other Are Option
+
+
+// Path Option Makes The Cookie Available Only At The /a and /a/b ................ Path. -> Not Available At /b But Available At /a/b
+// Expires At -> Date When Cookie Will Be Expired. Time Stamp In GMT
+
+// Note :
+// 1. The Name And Value Pair After EncodeURI Component Can Be Up To 4KB
+// 2. Total No Of Cookies Per Domain Is Limited To Arbitrary Number Around 20+ (Exact Number Is Browser Dependent)
+// 3. Cookies Are Sent With Each Request To The Server, So The Server Can Learn Who Sent The Request
+
+// Local Storage
+// Local Storage Is Web Storage Object Which Are Not Sent To Server With Each Request
+// Data Survives Page Refresh And Even After Full Restart
+
+// These Are Method Provided By Local Storage
+
+// 1. localStorage.setItem(key, value) -> Store Key Value Pair Or Update The Value If Key Is Already Present
+// 2. localStorage.getItem(key) -> Get The Value By Key
+// 3. localStorage.removeItem(key) -> Remove The Key Value Pair
+// 4. localStorage.clear() -> Clear The Entire Local Storage
+// 5. localStorage.key(index) -> Get The Key On A Given Position
+// 6. localStorage.length -> The Number Of Stored Items
+// We Can Use Both Key And Value As String
+
+// let key = prompt("Enter key you want to set")
+// let value = prompt("Enter value you want to set")
+
+// localStorage.setItem(key, value)
+
+// console.log(`The value at ${key} is ${localStorage.getItem(key)}`)
+
+// if (key == "red" || key == "blue") {
+// localStorage.removeItem(key)
+// }
+
+// if (key == 0) {
+// localStorage.clear()
+// }
+// console.log(localStorage.length)
+
+// We Can Get And Set Values Like An Object
+// localStorage.one = 1
+// alert(localStorage.one)
+// delete localStorage.one
+
+// Note:
+// 1. Both Key And Value Must Be String
+// 2. We Can Use The Two JSON Methods To Store Objects In Local Storage
+
+// JSON.stringify(object) -> Converts Objects To JSON Strings
+// JSON.parse(string) -> Converts String To Objects (Must Be Valid JSON)
+
+// Session Storage
+// Session Storage Exists For Only One Session. Data Survives Refresh But Not Close Of Browser
+
+// Used Less As Compared To Local Storage
+// Properties And Method Are Same As Local Storage But:
+// 1. Session Storage Data Survives Page Refresh But Not Close Of Browser
+// It Exists Only Within The Current Browser Tab. Another Tab With Same Page Will Have Empty Session Storage
+
+// 2. The Data Survives Page Refresh, But Not Closing / Opening Of Browser
+
+// Storage Event
+// When The Data Gets Updated In Local Storage Or Session Storage, Storage Event Triggered With These Properties:
+// 1. key -> The Key
+// 2. oldValue -> Previous Value
+// 3. newValue -> New Value
+// 4. url -> Page URL
+// 5. storageArea -> local or session
+
+// We Can Listen The OnStorage Event Of Window Which Is Triggered When Updates Are Made To The Same Storage From Other Documents
+
+// sessionStorage.getItem("name")
+// sessionStorage.clear()
+// sessionStorage.removeItem("name")
+// sessionStorage.setItem("name", "harry")
+// sessionStorage.removeItem("name")
+
+// Dusri Tab Dusra Page Different Session Storage
+
+// window.onstorage = (e) => {
+// alert("changed")
+// console.log(e)
+// }
+
+// Practice Set
+
+// Q1 Use a Free API From The Internet And Feed Your App With Live Data
+
+// Q2 Create A Note Saving App Which Stores Your Note To localStorage
+
+// Q3 Repeat Q2 And Fetch The Note Which User Entered In The Previous Question
+
+// Q4 Delete The Note In The Previous Question
+
+
+let url = "https://kontests.net/api/v1/all"
+let response = fetch(url)
+response.then((v) => {
+ return v.json()
+}).then((contests) => {
+ console.log(contests)
+ ihtml = ""
+ for (item in contests) {
+ console.log(contests[item])
+ ihtml += `
+
+
+
+
${contests[item].name}
+
Status is ${contests[item].status} and site is ${contests[item].site}
+
In 24 Hours? ${contests[item].in_24_hours}
+
Starts at: ${contests[item].start_time}
+
Starts at: ${contests[item].end_time}
+ Visit Contest
+
+
+ `
+ }
+ cardContainer.innerHTML = ihtml
+})
+
+/* ******************* NOTES APP (REMAINING QUESTIONS OF PRACTICE SET) *********** */
+// let n = localStorage.getItem("note")
+// alert("Your note is " + n)
+
+// let a = prompt("Enter your note")
+// if (a) {
+// localStorage.setItem("note", a)
+// }
+
+// let c = confirm("Do you want to delete your note?")
+// if (c) {
+// localStorage.removeItem("note")
+// alert("Note deleted successfully!")
+// }
diff --git a/Ch-10-Network-Request-And-Storing-Data/style.css b/Ch-10-Network-Request-And-Storing-Data/style.css
new file mode 100644
index 0000000..cd9ec62
--- /dev/null
+++ b/Ch-10-Network-Request-And-Storing-Data/style.css
@@ -0,0 +1,4 @@
+html {
+ height: 100%;
+ width: 100%;
+}
\ No newline at end of file
diff --git a/Ch-11-Object-Oriented-Programing.zip b/Ch-11-Object-Oriented-Programing.zip
new file mode 100644
index 0000000..2c47b93
Binary files /dev/null and b/Ch-11-Object-Oriented-Programing.zip differ
diff --git a/Ch-11-Object-Oriented-Programing/.gitignore b/Ch-11-Object-Oriented-Programing/.gitignore
new file mode 100644
index 0000000..40b878d
--- /dev/null
+++ b/Ch-11-Object-Oriented-Programing/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Ch-11-Object-Oriented-Programing/Readme.md b/Ch-11-Object-Oriented-Programing/Readme.md
new file mode 100644
index 0000000..ee44195
--- /dev/null
+++ b/Ch-11-Object-Oriented-Programing/Readme.md
@@ -0,0 +1,398 @@
+
+**Define a Constructor Function:**
+
+```javascript
+function Person(name, age) {
+ this.name = name;
+ this.age = age;
+}
+```
+
+**Add a Method to the Constructor Function's Prototype:**
+
+```javascript
+Person.prototype.sayHello = function() {
+ console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
+};
+```
+
+**Create a New Object Using the Constructor Function:**
+
+```javascript
+const person1 = new Person("Alice", 30);
+```
+
+**Call the Method on the Object:**
+
+```javascript
+person1.sayHello(); // Output: "Hello, my name is Alice and I'm 30 years old."
+```
+
+---
+
+## Prototypal Inheritance.
+
+
+```javascript
+// Define a constructor function
+function Person(name, age) {
+ this.name = name;
+ this.age = age;
+}
+
+// Add a method to the constructor function's prototype
+Person.prototype.sayHello = function() {
+ console.log("Hello, my name is " + this.name + " and I'm " + this.age + " years old.");
+};
+
+// Create a new object using the constructor function
+var person1 = new Person("Alice", 30);
+
+// Call the method on the object
+person1.sayHello(); // output: "Hello, my name is Alice and I'm 30 years old.
+```
+
+**Object-Oriented Programming in JavaScript with Examples [Updated 2024]**
+
+Object-Oriented Programming (OOP) in JavaScript is a paradigm focused on objects rather than functions. Unlike procedural programming, which structures programs as a sequence of logical steps, OOP models complex systems as interactive objects.
+
+This guide explores the core principles of OOP in JavaScript with practical examples.
+
+### Fundamentals of OOP in JavaScript
+
+1. **Objects and Classes**
+ - An object in JavaScript is a standalone entity with properties and a type.
+
+ ```javascript
+ const dog = {
+ breed: 'Labrador',
+ color: 'black',
+ bark() {
+ console.log('Woof!');
+ }
+ };
+ dog.bark(); // Output: Woof!
+ ```
+
+ - Classes, introduced in ES6, serve as templates for creating objects.
+
+ ```javascript
+ class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+ speak() {
+ console.log(`${this.name} makes a noise.`);
+ }
+ }
+ const animal = new Animal('Dog');
+ animal.speak(); // Output: Dog makes a noise.
+ ```
+
+2. **Encapsulation**
+ - Encapsulation involves hiding an object's internal representation from the outside.
+
+ ```javascript
+ class Car {
+ constructor(brand) {
+ this._brand = brand;
+ }
+ get brand() {
+ return this._brand;
+ }
+ set brand(newBrand) {
+ this._brand = newBrand;
+ }
+ }
+ const myCar = new Car('Ford');
+ console.log(myCar.brand); // Output: Ford
+ myCar.brand = 'BMW';
+ console.log(myCar.brand); // Output: BMW
+ ```
+
+3. **Inheritance**
+ - Inheritance allows a class to inherit properties and methods from another class.
+
+ ```javascript
+ class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+ speak() {
+ console.log(`${this.name} makes a noise.`);
+ }
+ }
+ class Dog extends Animal {
+ speak() {
+ console.log(`${this.name} barks.`);
+ }
+ }
+ const d = new Dog('Mitzie');
+ d.speak(); // Output: Mitzie barks.
+ ```
+
+4. **Polymorphism**
+ - Polymorphism enables objects of different classes to be treated as instances of a common superclass.
+
+ ```javascript
+ class Animal {
+ speak() {
+ console.log('Animal speaks');
+ }
+ }
+ class Cat extends Animal {
+ speak() {
+ console.log('Meow');
+ }
+ }
+ class Dog extends Animal {
+ speak() {
+ console.log('Woof');
+ }
+ }
+ function makeAnimalSpeak(animal) {
+ animal.speak();
+ }
+ makeAnimalSpeak(new Cat()); // Output: Meow
+ makeAnimalSpeak(new Dog()); // Output: Woof
+ ```
+
+5. **Abstraction**
+ - Abstraction involves creating simple models to represent complex real-world objects.
+
+ ```javascript
+ class Vehicle {
+ startEngine() {
+ console.log('Engine started');
+ }
+ stopEngine() {
+ console.log('Engine stopped');
+ }
+ }
+ class Car extends Vehicle {
+ startEngine() {
+ console.log('Car engine started');
+ }
+ }
+ const myCar = new Car();
+ myCar.startEngine(); // Output: Car engine started
+ ```
+
+### Advanced OOP Concepts in JavaScript
+
+6. **Constructors and the new Keyword**
+ - Constructors are special functions for creating and initializing objects.
+
+ ```javascript
+ class Person {
+ constructor(name, age) {
+ this.name = name;
+ this.age = age;
+ }
+ }
+ const person = new Person('Alice', 25);
+ console.log(person); // Output: Person { name: 'Alice', age: 25 }
+ ```
+
+7. **Methods — Instance, Static, and Prototype Methods**
+ - Methods in JavaScript can be instance, static, or prototype methods.
+
+ ```javascript
+ class Rectangle {
+ constructor(width, height) {
+ this.width = width;
+ this.height = height;
+ }
+ // Instance method
+ getArea() {
+ return this.width * this.height;
+ }
+ // Static method
+ static compareArea(rect1, rect2) {
+ return rect1.getArea() - rect2.getArea();
+ }
+ }
+ const rect1 = new Rectangle(5, 8);
+ const rect2 = new Rectangle(6, 7);
+ console.log(Rectangle.compareArea(rect1, rect2)); // Output: -2
+ ```
+
+8. **Getters and Setters**
+ - Getters and setters allow you to define Object Accessors (Computed Properties).
+
+ ```javascript
+ class Person {
+ constructor(firstName, lastName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ }
+ get fullName() {
+ return `${this.firstName} ${this.lastName}`;
+ }
+ set fullName(name) {
+ [this.firstName, this.lastName] = name.split(' ');
+ }
+ }
+ const person = new Person('John', 'Doe');
+ console.log(person.fullName); // Output: John Doe
+ person.fullName = 'Jane Smith';
+ console.log(person.fullName); // Output: Jane Smith
+ ```
+
+9. **Inheritance with extends and super**
+ - The `extends` keyword is used to create a child class from a parent class.
+
+ ```javascript
+ class Shape {
+ constructor(name) {
+ this.name = name;
+ }
+ move() {
+ console.log(`${this.name} moved`);
+ }
+ }
+ class Circle extends Shape {
+ constructor(radius) {
+ super('Circle');
+ this.radius = radius;
+ }
+ }
+ const myCircle = new Circle(5);
+ myCircle.move(); // Output: Circle moved
+ ```
+
+### Object-Oriented vs. Functional Programming in JavaScript
+
+**Differences Between OOP and Functional Programming:**
+- **State and Immutability:** OOP manages state within objects, which can change over time. Functional programming prefers immutable data structures and pure functions without side effects.
+- **Methodology:** OOP models real-world entities using objects and classes, while functional programming focuses on computation and avoids changing state.
+- **Code Reusability:** In OOP, reusability comes through inheritance and polymorphism. Functional programming achieves reusability through functions and higher-order functions.
+
+**When to Use OOP or Functional Programming:**
+- **Use OOP when:**
+ - You’re dealing with a complex system with clearly defined types and relationships.
+ - Your application’s state changes frequently and needs cohesive management.
+ - You prefer a modular, structured approach to organizing code.
+
+- **Use Functional Programming when:**
+ - You need a system with operations that don’t depend on or alter the state.
+ - Your focus is on data flow and transformations.
+ - You aim for code that’s easy to test and reason about, thanks to its immutability and purity.
+
+### Conclusion:
+Object-oriented programming in JavaScript offers a powerful way to structure and organize code, especially for complex applications. Although it differs from functional programming, both paradigms have unique strengths and can be combined within a single project. Understanding both OOP and functional programming makes you a more versatile and effective JavaScript developer.
+
+### Prototypal Inheritance.
+
+
+
+
+Here's how you can approach each of these practice problems:
+
+### Q1: Create a Class to Create a Complex Number. Create a Constructor to Set the Real and Imaginary Parts.
+```javascript
+class ComplexNumber {
+ constructor(real, imaginary) {
+ this.real = real;
+ this.imaginary = imaginary;
+ }
+}
+
+// Example usage:
+let num1 = new ComplexNumber(3, 4); // Complex number: 3 + 4i
+console.log(`Complex Number: ${num1.real} + ${num1.imaginary}i`);
+```
+
+### Q2: Write a Method to Add Two Complex Numbers in the Above Class.
+```javascript
+class ComplexNumber {
+ constructor(real, imaginary) {
+ this.real = real;
+ this.imaginary = imaginary;
+ }
+
+ add(otherComplex) {
+ return new ComplexNumber(
+ this.real + otherComplex.real,
+ this.imaginary + otherComplex.imaginary
+ );
+ }
+}
+
+// Example usage:
+let num1 = new ComplexNumber(3, 4);
+let num2 = new ComplexNumber(1, 2);
+let sum = num1.add(num2);
+console.log(`Sum: ${sum.real} + ${sum.imaginary}i`);
+```
+
+### Q3: Create a Class `Student` from a Class `Human`. Override a Method and See Changes.
+```javascript
+class Human {
+ speak() {
+ console.log("Hello, I am a human.");
+ }
+}
+
+class Student extends Human {
+ speak() {
+ console.log("Hello, I am a student.");
+ }
+}
+
+// Example usage:
+let person = new Human();
+person.speak(); // Output: "Hello, I am a human."
+
+let student = new Student();
+student.speak(); // Output: "Hello, I am a student."
+```
+
+### Q4: See if `Student` is an Instance of `Human` Using `instanceof` Keyword.
+```javascript
+console.log(student instanceof Human); // Output: true
+console.log(student instanceof Student); // Output: true
+console.log(person instanceof Student); // Output: false
+```
+
+### Q5: Use Getters and Setters to Set and Get the Real and Imaginary Parts of the Complex Number.
+```javascript
+class ComplexNumber {
+ constructor(real, imaginary) {
+ this._real = real;
+ this._imaginary = imaginary;
+ }
+
+ get real() {
+ return this._real;
+ }
+
+ set real(value) {
+ this._real = value;
+ }
+
+ get imaginary() {
+ return this._imaginary;
+ }
+
+ set imaginary(value) {
+ this._imaginary = value;
+ }
+}
+
+// Example usage:
+let num = new ComplexNumber(5, 6);
+console.log(`Before: ${num.real} + ${num.imaginary}i`);
+
+num.real = 7; // Using setter
+num.imaginary = 8; // Using setter
+
+console.log(`After: ${num.real} + ${num.imaginary}i`); // Using getter
+```
+
+### Summary:
+- **Q1**: We defined a `ComplexNumber` class with a constructor to initialize the real and imaginary parts.
+- **Q2**: Added a method to sum two complex numbers.
+- **Q3**: Demonstrated inheritance by creating a `Student` class from `Human` and overriding a method.
+- **Q4**: Used the `instanceof` keyword to check if an object is an instance of a particular class.
+- **Q5**: Implemented getters and setters to access and modify the real and imaginary parts of the complex number.
\ No newline at end of file
diff --git a/Ch-11-Object-Oriented-Programing/image.png b/Ch-11-Object-Oriented-Programing/image.png
new file mode 100644
index 0000000..0366088
Binary files /dev/null and b/Ch-11-Object-Oriented-Programing/image.png differ
diff --git a/Ch-11-Object-Oriented-Programing/index.html b/Ch-11-Object-Oriented-Programing/index.html
new file mode 100644
index 0000000..5232e30
--- /dev/null
+++ b/Ch-11-Object-Oriented-Programing/index.html
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+ replit
+
+
+
+
+ Hello world
+
+
+
+
\ No newline at end of file
diff --git a/Ch-11-Object-Oriented-Programing/script.js b/Ch-11-Object-Oriented-Programing/script.js
new file mode 100644
index 0000000..4e0f5d2
--- /dev/null
+++ b/Ch-11-Object-Oriented-Programing/script.js
@@ -0,0 +1,486 @@
+// [[Prototype]]
+// First Priority Object Method Ki Than Nahi Mila To Prototype Ka Method Use Karo
+// JavaScript Object Have A Special Property Called Prototype That Is Either Null Or Reference To Another Object
+
+// When We Try To Read A Property From An Object And It's Missing, JavaScript Will Take It From Its Prototype. This Is Called Prototypal Inheritance.
+
+// let a = {
+// name2: "Harry",
+// language: "JavaScript",
+// run: () => {
+// alert("self run")
+// }
+// }
+// console.log(a)
+
+
+// let p = {
+// run: () => {
+// alert("run")
+// }
+// }
+
+// p.__proto__ = {
+// name: "Jackie"
+// }
+
+// a.__proto__ = p
+// a.run()
+// console.log(a.name)
+
+// Setting Prototype
+// We Can Set Prototype By Setting __proto__ Property On Any Object. Now If We Read A Property From That Object, JavaScript Will Take It From The Object Itself And If It's Missing, JavaScript
+
+// If We Have A Method In Object, It Will Be Called From Object. If Its Missing In Object And Present In Prototype, It Will Be Called From Prototype.
+
+// Classes And Objects
+
+// In OOP A Class Is An Extensible Program Code Template For Creating Objects, Providing Initial Value For State (Member Variables) And Implementation Of Behavior (Member Functions)
+
+// Syntax:
+// class ClassName {
+// constructor() {
+// // initialise
+// }
+// // Function
+// method_name() {
+// // code
+// }
+// }
+
+// class RailwayForm {
+// submit() {
+// alert(this.name + ": Your form is submitted for train number: " + this.trainno)
+// }
+// cancel() {
+// alert(this.name + ": This form is cancelled for train number: " + this.trainno)
+// }
+// fill(givenname, trainno) {
+// this.name = givenname
+// Object Associated Property = Input Me A Rahi Value
+// this.trainno = trainno
+// }
+// }
+
+// // Create a form for Harry
+// let harryForm = new RailwayForm()
+// // Fill the form with Harry's details
+// harryForm.fill("Harry", 145316)
+
+// // Create a forms for Rohan
+// let rohanForm1 = new RailwayForm()
+// let rohanForm2 = new RailwayForm()
+// // Fill the forms with Rohan's details
+// rohanForm1.fill("Rohan", 222420)
+// rohanForm2.fill("Rohan", 2229211)
+
+// harryForm.submit()
+// rohanForm1.submit()
+// rohanForm2.submit()
+// rohanForm1.cancel()
+
+// We Can Than Use New Class() To Create An Object
+
+// Constructor Method
+// A Constructor Is A Special Method Which Is Automatically Called When An Object Is Created. -> Its Used To Initialize The Object.
+
+// Old
+
+// class RailwayForm {
+// constructor(givenname, trainno) {
+// console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno)
+// this.name = givenname
+// this.trainno = trainno
+// }
+
+// submit() {
+// alert(this.name + ": Your form is submitted for train number: " + this.trainno)
+// }
+// cancel() {
+// alert(this.name + ": This form is cancelled for train number: " + this.trainno)
+// }
+// }
+
+// // Create & fill a form for Harry
+// let harryForm = new RailwayForm("Harry", 145316)
+// // No need to Fill the form with Harry's details
+// // harryForm.fill()
+
+// // Create & fill a forms for Rohan
+// let rohanForm1 = new RailwayForm("Rohan", 222420)
+// let rohanForm2 = new RailwayForm("Rohan", 2229211)
+
+
+
+// harryForm.submit()
+// rohanForm1.submit()
+// rohanForm2.submit()
+// rohanForm1.cancel()
+
+// New
+
+// class RailwayForm {
+// constructor(givenname, trainno, address) {
+// console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno)
+// this.name = givenname
+// this.trainno = trainno
+// this.address = address
+// }
+
+// preview() {
+// alert(this.name + ": Your form is for Train number: " + this.trainno + " and your address is " + this.address)
+// }
+
+// submit() {
+// alert(this.name + ": Your form is submitted for train number: " + this.trainno)
+// }
+
+// cancel() {
+// alert(this.name + ": This form is cancelled for train number: " + this.trainno)
+// this.trainno = 0
+// }
+// }
+
+// let harryForm = new RailwayForm("Harry", 13488, "420, Pacific Ocean, Ocean, Bihar - 0000555")
+// harryForm.preview()
+// harryForm.submit()
+// harryForm.cancel()
+// harryForm.preview()
+
+
+// Class Inheritance
+
+// Class Inheritance Is A Way For One Class To Inherit All The Methods And Properties From Another Class. In JavaScript, It Is Done By Using Extends Keyword.
+
+// class Animal {
+// constructor(name, color) {
+// this.name = name
+// this.color = color
+// }
+// run() {
+// console.log(this.name + " is running!")
+// }
+// shout() {
+// console.log(this.name + " is barking!")
+// }
+// }
+
+// class Monkey extends Animal {
+// eatBanana() {
+// console.log(this.name + " is eating banana")
+// }
+// hide() {
+// console.log(`${this.name} is hiding`)
+// }
+// }
+
+// let ani = new Animal("Bruno", "white")
+// let m = new Monkey("Chimpu", "orange")
+
+// ani.shout()
+// m.eatBanana()
+// m.hide()
+// // ani.hide() //This will throw an error
+
+// Extend Keyword
+
+// Extend Keyword Is Used To Extend Another Class.
+
+
+// Class Child extends Parent
+
+// Parent Classes Is The Class From Which Other Class Inherits.
+// class Animal {
+// constructor(name, color) {
+// this.name = name
+// this.color = color
+// }
+// run() {
+// console.log(this.name + " is running")
+// }
+// shout() {
+// console.log(this.name + " is shouting")
+// }
+// }
+// // Child Class
+// class Monkey extends Animal {
+// eatBanana() {
+// console.log(this.name + " is eating banana")
+// }
+// }
+
+// Method Overriding
+// Method Overriding Is A Feature In OOP Language Where A Child Class Can Override A Parent Method.
+
+// class Employee {
+// constructor(name) {
+// console.log(`${name} - Employee's constructor is here`)
+// this.name = name
+// }
+// login() {
+// console.log(`Employee has logged in`);
+// }
+
+// logout() {
+// console.log(`Employee has logged out`);
+// }
+
+// requestLeaves(leaves) {
+// console.log(`Employee has requested ${leaves} leaves - Auto approved`)
+// }
+// }
+
+// class Programmer extends Employee {
+// constructor(name) {
+// super(name)
+// console.log(`This is a newly written constructor`)
+// }
+// // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically
+// // super(...args)
+// // }
+// requestCoffee(x) {
+// console.log(`Employee has requested ${x} coffees`)
+// }
+// requestLeaves(leaves) {
+// super.requestLeaves(4)
+// console.log("One extra is granted")
+// // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`)
+
+// }
+// }
+
+// let e = new Programmer("Harry")
+// e.login()
+// e.requestLeaves(3)
+
+// If We Create Our Own Implimentstion Of Run Method In Child Class, It Will Be Overridden.
+
+// Super Kewword
+// Super Keyword Is Used To Call The Parent Class Constructor.
+// When We Override A Method In Child Class, We Use Super Keyword To Call The Parent Class Method.
+
+// super(a,b) -> Call Parent Class Constructor
+
+
+// Overriding Constructor
+
+// With A Constructor, Things Are Bit Tricky/ Different. According To The Specifications , If A Class Extends Another Class And Has No Constructor. Than The Child Class Will Have A Constructor Automatically. -> By Default Its Generated By The JS Engine.
+
+// Default One
+// constructor(...args){ ---> If there is no constructor in the child class, this is created automatically
+// // super(...args)
+// // }
+
+// Constructor In Inheriting Classes Mus Call Super (...) And Do It Before Using This.
+// We Can Also Use super.method() In Child Class To Call Parent Class Method.
+
+// class Employee {
+// constructor(name) {
+// console.log(`${name} - Employee's constructor is here`)
+// this.name = name
+// }
+// login() {
+// console.log(`Employee has logged in`);
+// }
+
+// logout() {
+// console.log(`Employee has logged out`);
+// }
+
+// requestLeaves(leaves) {
+// console.log(`Employee has requested ${leaves} leaves - Auto approved`)
+// }
+// }
+
+// class Programmer extends Employee {
+// constructor(name) {
+// super(name)
+// console.log(`This is a newly written constructor`)
+// }
+// // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically
+// // super(...args)
+// // }
+// requestCoffee(x) {
+// console.log(`Employee has requested ${x} coffees`)
+// }
+// requestLeaves(leaves) {
+// super.requestLeaves(4)
+// console.log("One extra is granted")
+// // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`)
+
+// }
+// }
+
+// let e = new Programmer("Harry")
+// e.login()
+// e.requestLeaves(3)
+
+
+// Static Methods
+// Static Methods Are Methods Which Are Associated With A Class And Not With Any Instance Of It.
+
+// Static Method Are Used To Implement Logic Which Does Not Rely On Instance.
+
+// Static Method Are Used To Implement Function That Belong To A Class As A Whole. And Not To Any Particular Object.
+
+// We Can Assign Single Static Method;
+
+// Syntax:
+
+// class follow {
+// static method() {
+// console.log("This is a static method")
+// }
+// }
+
+// follow.method()
+
+// Static Methods Aren't Available For Individual Object
+
+// class Animal {
+// constructor(name) {
+// this.name = Animal.capitalize(name)
+// }
+// walk() {
+// alert("Animal " + this.name + " is walking")
+// }
+// static capitalize(name) {
+// return name.charAt(0).toUpperCase() + name.substr(1, name.length)
+// }
+// }
+
+// j = new Animal("jack")
+// j.walk()
+// console.log(j.capitalize("thisa")) // --- > this doesnt work
+
+// Getters And Setters
+
+// Getters And Setters Are Special Methods Which Are Used To Get And Set The Values Of An Object's Properties.
+
+// class Person {
+// constructor(name) {
+// this.name = name
+// }
+// fly() {
+// console.log("I am flying")
+// }
+// get name() {
+// return this._name
+// }
+// set name(newName) {
+// this._name = newName
+// }
+// }
+
+// class Animal {
+// constructor(name) {
+// this._name = name
+// }
+// fly() {
+// console.log("Mai ud rha hu")
+// }
+// get name() {
+// return this._name
+// }
+
+// set name(newName) {
+// this._name = newName
+// }
+
+// }
+
+// class Rabbit extends Animal {
+// eatCarrot() {
+// console.log("Eating carrot")
+// }
+// }
+
+// let a = new Rabbit("Bruno")
+// a.fly()
+// console.log(a.name)
+// a.name = "Jack"
+// console.log(a.name)
+// let c = 56
+
+// console.log(a instanceof Animal)
+// console.log(a instanceof Rabbit)
+// console.log(c instanceof Animal)
+
+
+// InstanceOf Operator
+// InstanceOf Operator Is Used To Check If An Object Is An Instance Of A Class.
+// Object It Belongs To Certain Class Or Not?
+// It Return True If Obj Belongs To The Class Or Any Other Class Inherited From It.
+// Syntax:
+
+// instanceof
+
+// Practice Set
+
+// Q1 Create A Class To Create A Complex Number. Create A Constructor To Set The Real And Imaginary Parts.
+
+// Q2 Write A Method To Add Two Complex Numbers In The Above Class.
+
+// Q3 Create A Class Student From A Class Human. Override A Method And See Changes.
+
+// Q4 See If Student Is An Instance Of Human Using InstanceOf Keyword.
+
+// Q5 Use Getters And Setters To Set And Get The Real And Imaginary Parts Of The Complex Number.
+
+
+// class Complex {
+// constructor(real, imaginary) {
+// this.real = real
+// this.imaginary = imaginary
+// }
+// add(num) {
+// this.real = this.real + num.real
+// this.imaginary = this.imaginary + num.imaginary
+
+// }
+
+// get real() {
+// return this._real
+// }
+
+// get imaginary() {
+// return this._imaginary
+// }
+
+// set imaginary(newImaginary) {
+// this._imaginary = newImaginary
+// }
+
+// set real(newReal) {
+// this._real = newReal
+// }
+// }
+
+// let a = new Complex(2, 4)
+// console.log(a.real, a.imaginary)
+// a.real = 10
+// a.imaginary = 10
+// let b = new Complex(6, 2)
+// a.add(b)
+// console.log(`${a.real}+${a.imaginary}i`)
+
+// class Human {
+// constructor(name, favfood) {
+// this.name = name
+// this.favfood = favfood
+// }
+// walk() {
+// console.log(this.name + "Human is walking")
+// }
+// }
+
+// class Student extends Human {
+// walk() {
+// console.log(this.name + ": Student is walking")
+// }
+// }
+
+// let o = new Student("Harry", "Bhindi")
+// o.walk()
+
+// console.log(o instanceof Human)
\ No newline at end of file
diff --git a/Ch-11-Object-Oriented-Programing/style.css b/Ch-11-Object-Oriented-Programing/style.css
new file mode 100644
index 0000000..cd9ec62
--- /dev/null
+++ b/Ch-11-Object-Oriented-Programing/style.css
@@ -0,0 +1,4 @@
+html {
+ height: 100%;
+ width: 100%;
+}
\ No newline at end of file
diff --git a/Ch-12-Advanced-JavaScript.zip b/Ch-12-Advanced-JavaScript.zip
new file mode 100644
index 0000000..e11d58a
Binary files /dev/null and b/Ch-12-Advanced-JavaScript.zip differ
diff --git a/Ch-12-Advanced-JavaScript/.gitignore b/Ch-12-Advanced-JavaScript/.gitignore
new file mode 100644
index 0000000..40b878d
--- /dev/null
+++ b/Ch-12-Advanced-JavaScript/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Ch-12-Advanced-JavaScript/Readme.md b/Ch-12-Advanced-JavaScript/Readme.md
new file mode 100644
index 0000000..4db8886
--- /dev/null
+++ b/Ch-12-Advanced-JavaScript/Readme.md
@@ -0,0 +1,96 @@
+### JavaScript Closures: An Overview
+
+**Definition**:
+A closure is a function that retains access to its lexical environment (the variables that were in scope at the time of the function’s creation) even after the outer function has returned. This allows the function to access those variables even when it is executed outside of its original context.
+
+**Key Concepts**:
+1. **Lexical Environment**:
+ - When a function is created in JavaScript, it has access to its own local scope, the scope of the outer function, and the global scope.
+ - The environment in which a function was declared is known as its *lexical environment*.
+
+2. **Inner Functions**:
+ - A closure is created when an inner function is defined inside an outer function and then the inner function is returned or passed outside of the outer function.
+ - The inner function has access to the variables declared in the outer function, even after the outer function has finished executing.
+
+3. **Persistent Data**:
+ - Closures allow you to create functions with persistent data. The inner function can "remember" the state of variables from its outer function's scope.
+
+**Example**:
+```javascript
+function outerFunction() {
+ let counter = 0; // local variable to outerFunction
+
+ function innerFunction() {
+ counter++; // modifying outer function's variable
+ console.log(counter);
+ }
+
+ return innerFunction;
+}
+
+const incrementCounter = outerFunction();
+incrementCounter(); // Output: 1
+incrementCounter(); // Output: 2
+incrementCounter(); // Output: 3
+```
+**Explanation**:
+- `outerFunction` creates a local variable `counter` and an `innerFunction` that increments and logs the counter.
+- `innerFunction` is returned and assigned to `incrementCounter`.
+- Even though `outerFunction` has finished executing, `incrementCounter` still has access to the `counter` variable because of the closure.
+
+**Uses of Closures**:
+1. **Data Privacy**:
+ - Closures can be used to create private variables in JavaScript.
+ - This is a common pattern for encapsulating data and preventing it from being modified directly.
+
+ ```javascript
+ function createCounter() {
+ let count = 0;
+ return {
+ increment: function() {
+ count++;
+ return count;
+ },
+ decrement: function() {
+ count--;
+ return count;
+ },
+ getCount: function() {
+ return count;
+ }
+ };
+ }
+
+ const counter = createCounter();
+ console.log(counter.increment()); // Output: 1
+ console.log(counter.decrement()); // Output: 0
+ console.log(counter.getCount()); // Output: 0
+ ```
+
+2. **Callbacks and Event Handlers**:
+ - Closures are frequently used in asynchronous programming, such as when setting up event handlers or dealing with callbacks.
+
+ ```javascript
+ function setup() {
+ let name = "Mozilla";
+ document.getElementById("btn").addEventListener("click", function() {
+ alert("Hello, " + name);
+ });
+ }
+ setup();
+ ```
+
+3. **Functional Programming**:
+ - In functional programming, closures are used to create higher-order functions, partially apply functions, or maintain state.
+
+**Common Pitfalls**:
+1. **Memory Leaks**:
+ - Closures can inadvertently cause memory leaks if not handled properly, as they retain references to their lexical scope even if not needed anymore.
+
+2. **Overuse**:
+ - Overusing closures can lead to complex and hard-to-maintain code. They should be used judiciously and with clear intent.
+
+**Conclusion**:
+- Closures are a powerful feature in JavaScript that allow functions to retain access to their lexical scope even after the outer function has finished executing.
+- They are widely used in various programming patterns and can be essential for creating private variables, handling callbacks, and more.
+- Understanding closures is crucial for mastering JavaScript, especially when dealing with asynchronous code or implementing advanced functional programming techniques.
\ No newline at end of file
diff --git a/Ch-12-Advanced-JavaScript/index.html b/Ch-12-Advanced-JavaScript/index.html
new file mode 100644
index 0000000..5232e30
--- /dev/null
+++ b/Ch-12-Advanced-JavaScript/index.html
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+ replit
+
+
+
+
+ Hello world
+
+
+
+
\ No newline at end of file
diff --git a/Ch-12-Advanced-JavaScript/script.js b/Ch-12-Advanced-JavaScript/script.js
new file mode 100644
index 0000000..bc29d1c
--- /dev/null
+++ b/Ch-12-Advanced-JavaScript/script.js
@@ -0,0 +1,296 @@
+// IIFE -> Immediately Invoked Function Expression
+
+// IIFE Is A JavaScript Function That Runs As Soon As It Is Defined
+// (function() {
+// console.log("IIFE");
+// })();
+
+// // It is used to avoid polluting the global namespace, execute an async-await, etc.
+
+// let a = () => {
+// return new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve(456)
+// }, 4000)
+// })
+// }
+
+// (async () => {
+// let b = await a()
+// console.log(b)
+// let c = await a()
+// console.log(c)
+// let d = await a()
+// console.log(d)
+// })()
+
+
+// console.log(d) // Throws error
+
+// Destructuring And Spread Operator
+// Destructuring Assignment Is Used To Unpack Values From An Array, Or Properties From An Object, Into Dedicated Variables, In JavaScript.
+
+// let arr = [3, 5, 8, 9, 12, 14]
+// No need to do this:
+// let a = arr[0]
+// let b = arr[1]
+// let [a, b, c, d, ...rest] = arr
+// console.log(a, b, c, d, rest)
+// let [a, , b, ...rest] = arr
+// console.log(a, b, rest)
+// let { a, b } = { a: 1, b: 5 }
+// console.log(a, b)
+
+// [10, x,....rest] =[10, 20, 30, 40, 50, 60]
+// x will be 20 rest will be [30, 40, 50, 60]
+
+// Spread Operator
+
+// Spread Syntax Allow An Iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals)
+// let arr1 = [3, 5, 8]
+// let obj1 = { ...arr1 }
+// console.log(obj1)
+
+// function sum(v1, v2, v3) {
+// return v1 + v2 + v3
+// }
+
+// console.log(sum(...arr1))
+
+// let obj2 = {
+// name: "Harry",
+// company: "Company xyz",
+// address: "XYZ"
+// }
+
+// console.log({ ...obj2, name: "John", company: "ABC" })
+// console.log({ name: "John", company: "ABC", ...obj2 }) // This will print the obj2 object without changing any values
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
+
+// Local, Global And Function Scope In JavaScript
+// var -> Global Scope
+// let and const -> Block Scope
+// Function Scope -> The variable declared inside a function, becomes local to the function.
+
+// let p = 9
+// function ax() {
+// let a = 8;
+// console.log(p)
+// console.log(a)
+// }
+
+// ax()
+// console.log(p)
+// console.log(a)
+
+
+// Hoisting In JavaScript
+// Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution
+
+// let a;
+// Following two lines will run successfully due to JavaScript hoisting
+// console.log(a)
+// greet()
+// var greet = function() {
+// console.log("Good morning")
+// }
+
+// var a = 9; // Declaration hoisted to the top but initialization is not
+// console.log(a)
+
+// Hoisting With Let And Var
+// let and const are not hoisted
+// console.log(num);
+// let num = 6; -> Throws an error
+// var num = 6; -> Doesn't throw an error
+// const num = 6; -> Throws an error
+
+// Function Expression And Class Expression Are Not Hoisted
+// Function Expression Me = Sign Ata He
+
+// Closer Set
+
+// A Closer Is A Function With Lexical Environment
+
+// function init() {
+// var name = 'Mozilla'; // name is a local variable created by init
+// function displayName() {
+// // displayName() is the inner function, a closure
+// console.log(name); // use variable declared in the parent function
+// }
+// name = "Harry"
+// return displayName;
+// }
+// let c = init();
+// c()
+
+
+// function returnFunc() {
+// const x = () => {
+// let a = 1
+// console.log(a)
+// const y = () => {
+// // let a = 2
+// console.log(a)
+// const z = () => {
+// // let a = 3
+// console.log(a)
+// }
+// z()
+// }
+// a = 999
+// y()
+// }
+// return x
+// }
+
+// let a = returnFunc()
+// a()
+
+// Closure -> Function + Its Lexical Environment
+// Reference Milta He
+
+// Lexical Environment -> The Environment Of The Function -> Mere Pass Nahi He To Mere Pass Ka Environment Me Ase Check Karega
+
+// Arrow Function
+
+// const sayHello = name => {
+// console.log("greeting" + " " + name)
+// console.log("hi")
+// }
+
+// const x = {
+// name: "Harry",
+// role: "Js Developer",
+// exp: 30,
+// show: function() {
+// // let that = this
+// // console.log(this)
+// setTimeout(() => {
+// // console.log(`The name is ${that.name}\nThe role is ${that.role}`)
+// console.log(`The name is ${this.name}\nThe role is ${this.role}`)
+// }, 2000)
+// }
+// }
+// sayHello("Harry", "Good Afternoon")
+// console.log(x.name, x.exp)
+// x.show()
+
+// Arrow Function Uses Lexical This
+
+// Practice Set
+
+// const a = async (text, n = 2) => {
+// return new Promise((resolve, reject) => {
+// setTimeout(() => {
+// resolve(text)
+// }, 1000 * n)
+// })
+// }
+
+// (
+// async () => {
+// let text = await a("Hello")
+// console.log(text)
+// text = await a("World")
+// console.log(text)
+// }
+// )()
+
+// function sum(a, b, c) {
+// return a + b + c
+// }
+
+// let x = [1, 3, 5]
+// console.log(sum(...x));
+
+// (async () => {
+// let text = await a("I am resolving after 1 second", 1)
+// console.log(text)
+// text = await a("I am resolving after 4 seconds", 4)
+// console.log(text)
+// }
+// )()
+
+// function simpleInterest(p, r, t) {
+// return (p * r * t) / 100;
+// }
+
+// console.log(simpleInterest(100, 5, 1))
+
+// Regex Expression Or Regular Expression
+// https://regexr.com/
+// const regex = /(Harry){2}/gi
+// const text = "Harryharry is a very very nice awesome nice very boy"
+// console.log(text.replace(regex, "VERY"))
+
+// Event Loop
+
+// Asynchronous CallBack
+// Sometimes the JavaScript code can take a lot of time and this can block the
+// page re render
+// JavaScript has asynchronous callbacks for non blocking behavior
+// JavaScript runtime can do only one thing at a time
+// Browser gives us other things which work along with the runtime like Web
+// APIs.
+// In node.js these are available as C++ APIs
+
+// setTimeout(function timer() {
+// console.log('You clicked the button!');
+// }, 2000);
+
+// console.log("Hi!");
+
+// setTimeout(function timeout() {
+// console.log("Click the button!");
+// }, 5000);
+
+// console.log("Welcome to loupe.");
+
+// Task Queue
+// JavaScript can do only one thing at a time
+// The rest are queued to the task queue waiting to be executed
+// When we run setTimeout, webapis will run a timer and push the function
+// provided to setTimeout to the task queue once the timer evis
+// These tasks will be pushed to the stack where they can executed
+
+// Event Loop
+
+// JavaScript has a runtime model based on an event loop, which is responsible
+// for executing the code, collecting and processing events, and executing queued
+// sub-tasks
+// The event loop pushes the tasks from the task queue to the call stack
+// setTimeout(func1, 0) can be used to defer a function until all the pending tasks
+// (so far) have been executed
+// We can see how these things work in action by visiting
+// For Understanding Call Stack In Js :http://latentflip.com/loupe/
+
+// Module In JS
+
+
+// const hello = ()=>{
+// console.log("Hello Harry")
+// }
+
+// const ahello = (name)=>{
+// console.log("Hello " + name)
+// }
+
+// module.exports = {hello, ahello};// same as below line
+// // module.exports = {hello: hello, ahello: ahello};
+
+// // ES6 Modules
+// export const hello = ()=>{
+// console.log("Hello Harry")
+// }
+
+// export const ahello = (name)=>{
+// console.log("Hello " + name)
+// }
+
+// const harry = ()=>{
+// console.log("Hello " + "Harry")
+// }
+
+// export default harry;
diff --git a/Ch-12-Advanced-JavaScript/style.css b/Ch-12-Advanced-JavaScript/style.css
new file mode 100644
index 0000000..cd9ec62
--- /dev/null
+++ b/Ch-12-Advanced-JavaScript/style.css
@@ -0,0 +1,4 @@
+html {
+ height: 100%;
+ width: 100%;
+}
\ No newline at end of file
diff --git a/Ch-4-String.zip b/Ch-4-String.zip
new file mode 100644
index 0000000..9af0d56
Binary files /dev/null and b/Ch-4-String.zip differ
diff --git a/Ch-4-String/Readme.md b/Ch-4-String/Readme.md
new file mode 100644
index 0000000..9ef73a5
--- /dev/null
+++ b/Ch-4-String/Readme.md
@@ -0,0 +1,218 @@
+```
+// String
+
+// A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Strings are immutable, meaning that once created, they cannot be changed. However, string methods can be used to manipulate and extract information from strings.
+
+// String are Used To Store And Manipulate Text
+
+// String -> Collection Of Characters
+
+// Single Quotes -> let name = 'dp';
+// Double Quotes -> let name = "dp";
+
+let name = "dp";
+// console.log(name[3]); -> undefined
+
+
+// Template Literals
+
+// After ES6 -> Template Literals Came In Use -> Use Back Tic
+
+let boy1 = "hmm"
+let boy2 = 'ok'
+
+// Print Hmm nice ok
+// let sentence = `boy1 "nice" 'is' boy2` -> We a Make String -> Use Single Or Double Quotes Both Usage Possible If String Made Through Back Tic
+
+// String Interpolation
+let sentence = `${boy1} nice ${boy2}`
+console.log(sentence)
+// hmm nice ok
+
+let fruit = `Bana\'na` -> Bana'na
+console.log(fruit)
+
+// \' -> Escape Character -> Count As One Character
+// \n -> New Line
+// \t -> Tab
+// \r -> Carrige Return
+
+
+ // String Method & Properties
+ // Accessing Characters:
+ // Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0.
+
+ // const message = 'Hello';
+ // console.log(message[0]); // Output: H
+ // console.log(message[3]); // Output: l
+
+ // String Concatenation:
+ // Strings can be concatenated using the + operator or the concat() method.
+
+
+ // const firstName = 'John';
+ // const lastName = 'Doe';
+ // const fullName = firstName + ' ' + lastName;
+ // console.log(fullName); // Output: John Doe
+
+ // // Using concat()
+ // const message = 'Hello, ';
+ // const name = 'John';
+ // const greeting = message.concat(name);
+ // console.log(greeting); // Output: Hello, John
+
+ // Finding Substrings:
+ // The indexOf() method returns the index of the first occurrence of a substring within a string. It returns -1 if the substring is not found.
+
+ // const message = 'Hello, world!';
+ // console.log(message.indexOf('world')); // Output: 7
+ // console.log(message.indexOf('open')); // Output: -1
+
+
+ // Extracting Substrings:
+ // The slice() method extracts a portion of a string based on the start and end indexes.
+
+ // const message = 'Hello, world!';
+ // console.log(message.slice(0, 5)); // Output: Hello
+ // console.log(message.slice(7)); // Output: world!
+
+ // Replacing Substrings:
+ // The replace() method replaces a specified substring with another substring.
+
+ // const message = 'Hello, John!';
+ // console.log(message.replace('John', 'Alice')); // Output: Hello, Alice!
+
+ // Splitting Strings:
+ // The split() method splits a string into an array of substrings based on a specified delimiter.
+
+ // const message = 'Hello, World!';
+ // console.log(message.split(' ')); // Output: ["Hello,", "World!"]
+
+
+ // Checking if a String Contains a Substring:
+ // The includes() method checks if a string contains a specified substring and returns true or false.
+
+ // const message = 'Hello, World!';
+ // console.log(message.includes('World')); // Output: true
+ // console.log(message.includes('open')); // Output: false
+
+ // String Length:
+ // The length property returns the number of characters in a string.
+
+ // const message = 'Hello, world!';
+ // console.log(message.length); // Output: 13
+
+ // String Slice:
+ // The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string.
+
+ // const message = 'Hello, world!';
+ // console.log(message.slice(7)); // Output: world!
+ // console.log(message.slice(0, 5)); // Output: Hello
+
+
+ // String Substring:
+ // The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string.
+
+
+ // const message = 'Hello, world!';
+ // console.log(message.substring(7)); // Output: world!
+ // console.log(message.substring(0, 5)); // Output: Hello
+
+
+ // String Substr:
+ // The substr() method extracts a portion of a string based on the start index and length. It returns a new string.
+
+
+ // const message = 'Hello, world!';
+ // console.log(message.substr(7)); // Output: world!
+ // console.log(message.substr(0, 5)); // Output: Hello
+
+ // String Replace:
+
+ // The replace() method replaces a specified substring with another substring. It returns a new string.
+
+ // const message = 'Hello, John!';
+ // console.log(message.replace('John', 'Alice')); // Output: Hello, Alice!
+
+ // String ReplaceAll:
+ // The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021)
+
+
+ // const message = 'Hello, John! John is a good guy.';
+ // console.log(message.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy.
+
+ // String toUpperCase and toLowerCase:
+ // The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string.
+
+
+ // const message = 'Hello, world!';
+ // console.log(message.toUpperCase()); // Output: HELLO, WORLD!
+ // console.log(message.toLowerCase()); // Output: hello, world!
+
+
+ // String Concatenation:
+ // The concat() method concatenates two or more strings and returns a new string.
+
+
+ // const firstName = 'John';
+ // const lastName = 'Doe';
+ // console.log(firstName.concat(' ', lastName)); // Output: John Doe
+
+
+ // String Trim:
+ // The trim() method removes whitespace from both ends of a string and returns a new string.
+
+ // const message = ' Hello, world! ';
+ // console.log(message.trim()); // Output: Hello, world!
+
+
+ // String TrimStart and TrimEnd:
+ // The trimStart() and trimEnd() methods remove whitespace from the beginning and end of a string, respectively. They return a new string. (Available from ECMAScript 2021)
+
+ // const message = ' Hello, world! ';
+ // console.log(message.trimStart()); // Output: Hello, world!
+ // console.log(message.trimEnd()); // Output: Hello, world!
+
+ // String PadStart and PadEnd:
+ // The padStart() and padEnd() methods pad a string with a specified character to a given length. They return a new string. (Available from ECMAScript 2017)
+
+ // const message = 'Hello';
+ // console.log(message.padStart(10, '*')); // Output: *****Hello
+ // console.log(message.padEnd(10, '-')); // Output: Hello-----
+
+
+ // String CharAt and CharCodeAt:
+ // The charAt() method returns the character at a specified index in a string.
+ // The charCodeAt() method returns the Unicode value of the character at a specified index in a string.
+
+ // const message = 'Hello';
+ // console.log(message.charAt(0)); // Output: H
+ // console.log(message.charCodeAt(0)); // Output: 72
+
+
+ // String Split:
+ // The split() method splits a string into an array of substrings based on a specified delimiter.
+
+ // const message = 'Hello, World!';
+ // console.log(message.split(',')); // Output: ["Hello", " World!"]
+
+ // Method
+ // String length
+ // String slice()
+ // String substring()
+ // String substr()
+ // String replace()
+ // String replaceAll()
+ // String toUpperCase()
+ // String toLowerCase()
+ // String concat()
+ // String trim()
+ // String trimStart()
+ // String trimEnd()
+ // String padStart()
+ // String padEnd()
+ // String charAt()
+ // String charCodeAt()
+ // String split()
+
+```
\ No newline at end of file
diff --git a/Ch-4-String/index.js b/Ch-4-String/index.js
new file mode 100644
index 0000000..225a313
--- /dev/null
+++ b/Ch-4-String/index.js
@@ -0,0 +1,183 @@
+// Strings
+
+// A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Strings are immutable, meaning that once created, they cannot be changed. However, string methods can be used to manipulate and extract information from strings.
+
+// Strings are used to store and manipulate text
+
+// String -> Collection of characters
+
+// Single Quotes -> let name = 'dp';
+// Double Quotes -> let name = "dp";
+
+let name = "dp";
+// console.log(name[3]); -> undefined
+
+// Template Literals
+
+// After ES6, Template Literals came into use, utilizing backticks (`).
+
+let boy1 = "hmm";
+let boy2 = 'ok';
+
+// Print "hmm nice ok"
+// let sentence = `boy1 "nice" 'is' boy2` -> We make a string using single or double quotes, both usage possible if string is made through backticks
+
+// String Interpolation
+let sentence = `${boy1} nice ${boy2}`;
+console.log(sentence); // Output: hmm nice ok
+
+let fruit = `Bana\'na`; // Bana'na
+console.log(fruit);
+
+// \' -> Escape character -> Count as one character
+// \n -> New line
+// \t -> Tab
+// \r -> Carriage return
+
+// String Methods & Properties
+
+// Accessing Characters:
+// Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0.
+
+const message = 'Hello';
+console.log(message[0]); // Output: H
+console.log(message[3]); // Output: l
+
+// String Concatenation:
+// Strings can be concatenated using the + operator or the concat() method.
+
+const firstName = 'John';
+const lastName = 'Doe';
+const fullName = firstName + ' ' + lastName;
+console.log(fullName); // Output: John Doe
+
+// Using concat()
+const greetingMessage = 'Hello, ';
+const nameConcat = 'John';
+const greeting = greetingMessage.concat(nameConcat);
+console.log(greeting); // Output: Hello, John
+
+// Finding Substrings:
+// The indexOf() method returns the index of the first occurrence of a substring within a string. It returns -1 if the substring is not found.
+
+const welcomeMessage = 'Hello, world!';
+console.log(welcomeMessage.indexOf('world')); // Output: 7
+console.log(welcomeMessage.indexOf('open')); // Output: -1
+
+// Extracting Substrings:
+// The slice() method extracts a portion of a string based on the start and end indexes.
+
+console.log(welcomeMessage.slice(0, 5)); // Output: Hello
+console.log(welcomeMessage.slice(7)); // Output: world!
+
+// Replacing Substrings:
+// The replace() method replaces a specified substring with another substring.
+
+const personalizedMessage = 'Hello, John!';
+console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice!
+
+// Splitting Strings:
+// The split() method splits a string into an array of substrings based on a specified delimiter.
+
+console.log(welcomeMessage.split(' ')); // Output: ["Hello,", "world!"]
+
+// Checking if a String Contains a Substring:
+// The includes() method checks if a string contains a specified substring and returns true or false.
+
+console.log(welcomeMessage.includes('World')); // Output: true
+console.log(welcomeMessage.includes('open')); // Output: false
+
+// String Length:
+// The length property returns the number of characters in a string.
+
+console.log(welcomeMessage.length); // Output: 13
+
+// String Slice:
+// The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string.
+
+console.log(welcomeMessage.slice(7)); // Output: world!
+console.log(welcomeMessage.slice(0, 5)); // Output: Hello
+
+// String Substring:
+// The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string.
+
+console.log(welcomeMessage.substring(7)); // Output: world!
+console.log(welcomeMessage.substring(0, 5)); // Output: Hello
+
+// String Substr:
+// The substr() method extracts a portion of a string based on the start index and length. It returns a new string.
+
+console.log(welcomeMessage.substr(7)); // Output: world!
+console.log(welcomeMessage.substr(0, 5)); // Output: Hello
+
+// String Replace:
+// The replace() method replaces a specified substring with another substring. It returns a new string.
+
+console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice!
+
+// String ReplaceAll:
+// The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021)
+
+const repetitiveMessage = 'Hello, John! John is a good guy.';
+console.log(repetitiveMessage.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy.
+
+// String toUpperCase and toLowerCase:
+// The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string.
+
+console.log(welcomeMessage.toUpperCase()); // Output: HELLO, WORLD!
+console.log(welcomeMessage.toLowerCase()); // Output: hello, world!
+
+// String Concatenation:
+// The concat() method concatenates two or more strings and returns a new string.
+
+console.log(firstName.concat(' ', lastName)); // Output: John Doe
+
+// String Trim:
+// The trim() method removes whitespace from both ends of a string and returns a new string.
+
+const messageWithWhitespace = ' Hello, world! ';
+console.log(messageWithWhitespace.trim()); // Output: Hello, world!
+
+// String TrimStart and TrimEnd:
+// The trimStart() and trimEnd() methods remove whitespace from the beginning and end of a string, respectively. They return a new string. (Available from ECMAScript 2021)
+
+console.log(messageWithWhitespace.trimStart()); // Output: Hello, world!
+console.log(messageWithWhitespace.trimEnd()); // Output: Hello, world!
+
+// String PadStart and PadEnd:
+// The padStart() and padEnd() methods pad a string with a specified character to a given length. They return a new string. (Available from ECMAScript 2017)
+
+const paddedMessage = 'Hello';
+console.log(paddedMessage.padStart(10, '*')); // Output: *****Hello
+console.log(paddedMessage.padEnd(10, '-')); // Output: Hello-----
+
+// String CharAt and CharCodeAt:
+// The charAt() method returns the character at a specified index in a string.
+// The charCodeAt() method returns the Unicode value of the character at a specified index in a string.
+
+console.log(message.charAt(0)); // Output: H
+console.log(message.charCodeAt(0)); // Output: 72
+
+// String Split:
+// The split() method splits a string into an array of substrings based on a specified delimiter.
+
+console.log(welcomeMessage.split(',')); // Output: ["Hello", " World!"]
+
+ // Method summary:
+ // String length
+ // String slice()
+ // String substring()
+ // String substr()
+ // String replace()
+ // String replaceAll()
+ // String toUpperCase()
+ // String toLowerCase()
+ // String concat()
+ // String trim()
+ // String trimStart()
+ // String trimEnd()
+ // String padStart()
+ // String padEnd()
+ // String charAt()
+ // String charCodeAt()
+ // String split()
\ No newline at end of file
diff --git a/Ch-6-JS-In-Browser.zip b/Ch-6-JS-In-Browser.zip
new file mode 100644
index 0000000..26baca2
Binary files /dev/null and b/Ch-6-JS-In-Browser.zip differ
diff --git a/Ch-6-JS-In-Browser/.gitignore b/Ch-6-JS-In-Browser/.gitignore
new file mode 100644
index 0000000..40b878d
--- /dev/null
+++ b/Ch-6-JS-In-Browser/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Ch-6-JS-In-Browser/index.html b/Ch-6-JS-In-Browser/index.html
new file mode 100644
index 0000000..5232e30
--- /dev/null
+++ b/Ch-6-JS-In-Browser/index.html
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+ replit
+
+
+
+
+ Hello world
+
+
+
+
\ No newline at end of file
diff --git a/Ch-6-JS-In-Browser/script.js b/Ch-6-JS-In-Browser/script.js
new file mode 100644
index 0000000..24b2f43
--- /dev/null
+++ b/Ch-6-JS-In-Browser/script.js
@@ -0,0 +1,75 @@
+// Element Tab -> All Element
+// Onsole Tab -> All The Error Plus Logs
+// Network Tab -> All The Network Request And Requirement
+
+// External File For Js -> File Cache Ho Jati he So Website Fast WOrk Karti He
+// We Can Add Js In Script Tag Also
+//
+//
+
+// Separation Of Concern and Cashing
+
+// Js Console Object
+// console.log(console)
+// console.error(error)
+// console.assert(assert)
+// console.clear()
+// console.table(table)
+// console.warn(warn)
+// console.info(info)
+// console.time(time)
+// console.timeEnd(timeEnd)
+
+// List All Method
+// console.log(console)
+
+// Output And Return Type Is There
+// console.log("Hey Darshan")
+// Output :
+// Hey Darshan
+// Undefined
+
+// Alert Prompt And Confirm
+// Alert -> Alert Box Show Karta Hai
+// Prompt -> Prompt Box Show Karta Hai -> Input Lene Ke Liye
+// Confirm -> Confirm Box Show Karta Hai -> Yes Or No Lene Ke Liye
+
+// alert("Enter The Value Of A")
+// let a = prompt("Enter A Here: ")
+// let a = prompt("Enter A Here: ", "578") // Default Value
+// document.write(a)
+
+
+// Confirm -> Yes Or No Lene Ke Liye
+// let write = confirm("Do You Want To Write It To The Page")
+// if (write) {
+// document.write(a)
+// } else {
+// document.write("Please Allow Me To Write")
+// }
+
+// This Will Stop Screen Exicution Thats Why Not Suggested To Use That In User Side Plus Look Like Olde Vintage Website So -> Use In Admin Panel
+
+// BOM And DOM
+
+// BOM -> Browser Object Model
+// DOM -> Document Object Model
+console.log(window)
+// window.console.log(window) -> Same Work Above
+
+// window is global object under that -> Bom , Dom , Js Core Feture Lies
+
+// Apke Pure HTML Page ko Document Represent Karta Hai -> Pure Page Ka Object Banke Usko Document Name De Diya Gaya He
+console.log(document)
+document.body.style.background = "yellow"
+
+
+
+// BOM (Browser Object Model):
+// The Browser Object Model represents the browser window or tab itself. It provides additional objects and properties that allow you to control the browser's behavior and interact with the user. The window object acts as the global object in JavaScript and serves as the entry point to the BOM. It provides properties and methods to control the browser's behavior, such as window.location to manipulate the URL, window.alert() to display alert messages, and window.open() to open new browser windows or tabs.
+
+
+// Location href = "https://dpvasani56.com" -> Redirect To Another URL
+
+// console.log(window) => All Method
+// Window Object -> Global Object
diff --git a/Ch-6-JS-In-Browser/style.css b/Ch-6-JS-In-Browser/style.css
new file mode 100644
index 0000000..2e59ed3
--- /dev/null
+++ b/Ch-6-JS-In-Browser/style.css
@@ -0,0 +1,5 @@
+html {
+ height: 100%;
+ width: 100%;
+ /* background: red; */
+}
\ No newline at end of file
diff --git a/Ch-7-Js-DOM.zip b/Ch-7-Js-DOM.zip
new file mode 100644
index 0000000..55246ca
Binary files /dev/null and b/Ch-7-Js-DOM.zip differ
diff --git a/Ch-7-Js-DOM/.gitignore b/Ch-7-Js-DOM/.gitignore
new file mode 100644
index 0000000..40b878d
--- /dev/null
+++ b/Ch-7-Js-DOM/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Ch-7-Js-DOM/Readme.md b/Ch-7-Js-DOM/Readme.md
new file mode 100644
index 0000000..2a6fd2d
--- /dev/null
+++ b/Ch-7-Js-DOM/Readme.md
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/Ch-7-Js-DOM/image.png b/Ch-7-Js-DOM/image.png
new file mode 100644
index 0000000..4b166b4
Binary files /dev/null and b/Ch-7-Js-DOM/image.png differ
diff --git a/Ch-7-Js-DOM/index.html b/Ch-7-Js-DOM/index.html
new file mode 100644
index 0000000..25ef30a
--- /dev/null
+++ b/Ch-7-Js-DOM/index.html
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+ replit
+
+
+
+
+
+
+ Home
+ About
+ Project
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Ch-7-Js-DOM/script.js b/Ch-7-Js-DOM/script.js
new file mode 100644
index 0000000..6a75431
--- /dev/null
+++ b/Ch-7-Js-DOM/script.js
@@ -0,0 +1,138 @@
+// HTML Ko Convert Kar Diya He Js Object Me -> All Node Are Object
+// Text Node
+// Element Node
+// Comment Node
+
+// Auto Correction In HTML -> If Any Error In HTML Then It Will Be Auto Corrected
+
+// Walking The DOM
+
+// DOM Tree Traversal
+// document.body -> Page Body Tag
+// document.documentElement -> HTML Tag -> Page
+// document.head -> Head Tag
+// document.title -> String
+
+// document.body can be Null If The JavaScript Is Written Before The Body Tag
+// Children Of An Element -> Direct As Well As Deeply Nested Elements Of An Element Are Called Its Children
+
+// Child Nodes: Elements That Are Direct Children For Example Head And Body Are Children Of
+
+// Descendant Nodes: All Necessary Nodes Are Called Descendant Nodes For Example Head, Body, Title, Meta, Etc. Are Descendant Nodes Of
+
+// All Nested Elements , CHildren , Their Children And So On Are Called Their Siblings
+
+// First Child -> First Element Child -> element.firstChild
+// Last Child -> Last Element Child -> element.lastChild
+// Child Nodes (Element.childNodes) -> All Children
+
+// Following Are Always True
+// element.firstChild === element.childNodes[0]
+// element.lastChild === element.childNodes[element.childNodes.length - 1]
+
+// There Is Also A Method Element.hasChildNodes() To Check Whether There Are Any Child Nodes (Element.childNodes) Or Not
+
+// Child Nodes Are Not An Array But Can Be Converted Into Array -> Array.from(collection)
+
+// Child Nodes Look Like An Array But Actually Are Not But Its A Collection -> We Can Use Array Methods On It By Converting It Into Array.from(collection) To Convert It Into Array -> Array Methods Will Not Work On It
+
+// Notes On Dom Collection
+// They Are Read Only
+// They Are Live Element.childNodes Variable (Reference) Will Be Updated Automatically If Child Nodes Of The Element Is Changed
+// They Are Iterable Using For...Of Loop
+
+// Siblings And Their Parents
+
+// Siblings Are Nodes That Are Children Of The Same Parent
+// For Example And Are Siblings. Siblings Have Same Parent In This Case
+// Is Said To Be The "Next" Or "Right" Sibling Of , Is Said To Be The "Previous" Or "Left" Sibling Of
+// The Next Sibling Is In NextSibling Property , And The Previous One Is In previousSibling Property
+// The Parent Is In parentNode Property
+// alert(document.documentElement.parentNode) -> Document
+// alert(document.documentElement.parentElement) -> Null
+// parentElement -> Ak Element Hai To Hi Return Hoga Verna Null Return Hoga
+
+// console.log(document.body.firstChild)
+// a = document.body.firstChild
+// console.log(a.parentNode)
+// console.log(a.parentElement)
+// console.log(a.firstChild.nextSibling)
+
+
+
+// Element Only Navigation
+
+// Sometimes We Don't Want Text Or Comment Nodes. Some Links Only Take Element Nodes Into Account. For Example -> document.previousElementSibling -> Previous Sibling Which Is An Element
+
+
+// let b = document.body
+// console.log("First Child Of b Is : ", b.firstChild) // -> Kisi Bhi Tarah Ka First Childe Dekhne Ko Mil Sakta He Chahe Vo text Node Hi Kyu Na Ho
+// console.log("First Element Child Of b Is : ", b.firstElementChild)
+// Only Element Type Ka First Child Dekhne Ko Milta He
+
+// const changeBgRed =()=>{
+// document.body.firstElementChild.style.background = "red"
+
+// }
+
+// document.previousElementSibling -> Previous Sibling Which Is An Element
+// document.nextElementSibling -> Next Sibling Which Is An Element
+// document.firstElementChild -> First Element Child
+// document.lastElementChild -> Last Element Child
+
+// Table Links
+// Certain DOM Elements May Provide Additional Properties Specific To Their Type For Example Table Elements Support -> table.rows -> Collection Of Tr Elements
+
+// table.rows -> Collection Of Tr Elements
+// table.caption -> Reference To
+// table.tHead -> Reference To
+// table.tFoot -> Reference To
+// table.tBodies -> Collection Of Elements
+// tbody.rows -> Collection Of Inside
+// tr.cells -> Collection Of Td And Th
+// tr.sectionRowIndex -> Index Of Tr In It's Section
+// tr.rowIndex -> Row Number Starting From 0
+// td.cellIndex -> No Of Cells In Row
+
+
+// Searching The DOM
+// document.getElementById() -> To Search Element By Id
+// document.querySelectorAll(.card-title) -> To Search Multiple Elements With Same CSS Selector
+// document.querySelector() -> To Search Single Element With CSS Selector
+// document.getElementsByTagName() -> To Search Element By Tag Name
+// document.getElementsByClassName() -> To Search Element By Class Name
+// document.getElementsByName() -> To Search Element By Name Attribute
+
+// let ctitle = document.getElementsByClassName("card-title")[0]
+// console.log(document.quarySelector(".card-title").getElemetByClassName("card-title"))
+
+// No S -> Return One Element
+// S -> Return All Elements -> Elements
+
+// Matches, Closest & Contains Methods
+// elem.matches(CSS) -> To Check If Element Matches The Given CSS Selector
+// elem.closest(CSS) -> To Look For The Nearest ancestor That Matches The Given CSS Selector.
+// No Than Go to Perent Hai TO Return So And So
+
+// let id1 = document.getElementById("id1")
+// let sp1 = document.getElementById("sp1")
+// console.log(id1.matches(".class"))
+
+// elem.contains(elem) -> Returns True If Element B Is Inside Element A (A Descendant Of B) Or When Element A == Element B
+
+
+// Chapter 7 Practice Set
+// Q1 -> Create A Navbar And Change The Color Of Its First Element To Red
+// document.getElementsByTagName("nav")[0].firstElementChild.style.color = "red"
+// Q2 -> Create A Table Using JavaScript Which Background Color To Green
+// document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
+// Q3 -> Create An Element With 3 Children. Now Change The Color Of First And Last Element To Green
+// document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
+// document.getElementsByTagName("nav")[0].lastElementChild.style.color = "green"
+// Q4 -> Write A JavaScript Code To Change Background Of All Tags To Cyan
+// Array.from(document.getElementsByTagName("li")).forEach((element) => {
+// element.style.background = "cyan";
+// })
+// Q5 -> Which Of The Following Is Used To Look For The Farthest Ancestor That Matches A Given CSS Selector
+// (a) matches (b) closest (c) contains (d) none of these
+// Ans -> None Of These
diff --git a/Ch-7-Js-DOM/style.css b/Ch-7-Js-DOM/style.css
new file mode 100644
index 0000000..cd9ec62
--- /dev/null
+++ b/Ch-7-Js-DOM/style.css
@@ -0,0 +1,4 @@
+html {
+ height: 100%;
+ width: 100%;
+}
\ No newline at end of file
diff --git a/Ch-8-Events-And-Other-DOM-Properties.zip b/Ch-8-Events-And-Other-DOM-Properties.zip
new file mode 100644
index 0000000..b8d87b0
Binary files /dev/null and b/Ch-8-Events-And-Other-DOM-Properties.zip differ
diff --git a/Ch-8-Events-And-Other-DOM-Properties/.gitignore b/Ch-8-Events-And-Other-DOM-Properties/.gitignore
new file mode 100644
index 0000000..40b878d
--- /dev/null
+++ b/Ch-8-Events-And-Other-DOM-Properties/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Ch-8-Events-And-Other-DOM-Properties/Readme.md b/Ch-8-Events-And-Other-DOM-Properties/Readme.md
new file mode 100644
index 0000000..4a57062
--- /dev/null
+++ b/Ch-8-Events-And-Other-DOM-Properties/Readme.md
@@ -0,0 +1,461 @@
+Here's a JavaScript code snippet to demonstrate the use of `tagName` and `nodeName` properties:
+
+```javascript
+// HTML structure for reference
+//
+//
This is a paragraph.
+//
+//
This is a span element.
+//
This is a text node.
+//
+
+document.addEventListener("DOMContentLoaded", () => {
+ // Select the example div
+ const exampleDiv = document.getElementById("example");
+
+ // Iterate over all child nodes
+ exampleDiv.childNodes.forEach(node => {
+ // Print nodeName for all nodes
+ console.log("nodeName:", node.nodeName);
+
+ // Print tagName if the node is an element
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ console.log("tagName:", node.tagName);
+ }
+ });
+});
+```
+
+In this code:
+
+- `node.nodeName` is used to get the node name of each child node, which is defined for any type of node (Element, Text, Comment, etc.).
+- `node.tagName` is used to get the tag name, but only if the node is an element node (`node.nodeType === Node.ELEMENT_NODE`).
+
+When this script runs, it will log the `nodeName` for all child nodes of the `exampleDiv` and the `tagName` for element nodes. For example, it will output:
+
+```
+nodeName: #text
+nodeName: P
+tagName: P
+nodeName: #comment
+nodeName: SPAN
+tagName: SPAN
+nodeName: TEXT
+tagName: TEXT
+```
+
+
+## Insertion Through DOM
+
+```html
+
+
+
+
+ DOM Manipulation
+
+
+ Original Content
+
+
+
+```
+
+### Explanation:
+
+1. **`innerHTML`**:
+ - Sets or retrieves the HTML content inside an element.
+ - Here, it appends an `Hello World! ` to the existing content of the `container` div.
+
+2. **`document.createElement()`**:
+ - Creates a new HTML element.
+ - In this case, a new `div` is created, its inner HTML is set, and it is appended to the `container` div. Additionally, a class name `alert` is assigned.
+
+3. **`document.createTextNode()`**:
+ - Creates a new text node.
+ - This text node is appended to the `container` div.
+
+4. **`node.append()`**:
+ - Inserts nodes or strings after the last child of the specified parent node.
+ - Here, a new `div` with a paragraph is appended to the `container` div.
+
+5. **`node.prepend()`**:
+ - Inserts nodes or strings before the first child of the specified parent node.
+ - A new `div` with a paragraph is prepended to the `container` div.
+
+6. **`node.before()`**:
+ - Inserts nodes or strings before the specified node.
+ - A new `div` with a paragraph is inserted before the `container` div.
+
+7. **`node.after()`**:
+ - Inserts nodes or strings after the specified node.
+ - A new `div` with a paragraph is inserted after the `container` div.
+
+8. **`node.replaceWith()`**:
+ - Replaces the specified node with a given node.
+ - The `container` div is replaced with a new `div` containing a paragraph.
+
+
+## Insertion Method
+
+```html
+
+
+
+
+ DOM Manipulation
+
+
+ I am start of this container (outer)
+
+ I am start of this container (inner)
+
I am the first element
+ I am end of this container (inner)
+
+ I am end of this container (outer)
+
+
+
+```
+
+```javascript
+// script.js
+
+// 1. innerHTML
+let container = document.querySelector('.container');
+container.innerHTML = container.innerHTML + 'Hello World! ';
+
+// Output after innerHTML:
+// I am start of this container (outer)
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
+// I am end of this container (outer)
+
+// 2. document.createElement()
+let newDiv = document.createElement('div');
+newDiv.innerHTML = 'Hello World! ';
+container.appendChild(newDiv);
+newDiv.className = "alert";
+
+// Output after createElement and appendChild:
+// I am start of this container (outer)
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
Hello World!
+//
+// I am end of this container (outer)
+
+// 3. document.createTextNode()
+let textNode = document.createTextNode('This Is Text Node');
+container.appendChild(textNode);
+
+// Output after createTextNode:
+// I am start of this container (outer)
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
Hello World!
+// This Is Text Node
+//
+// I am end of this container (outer)
+
+// Node Insertion Methods
+
+// 4. node.append()
+let appendDiv = document.createElement('div');
+appendDiv.innerHTML = 'This is appended.
';
+container.append(appendDiv);
+
+// Output after node.append():
+// I am start of this container (outer)
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
Hello World!
+// This Is Text Node
+//
+//
+// I am end of this container (outer)
+
+// 5. node.prepend()
+let prependDiv = document.createElement('div');
+prependDiv.innerHTML = 'This is prepended.
';
+container.prepend(prependDiv);
+
+// Output after node.prepend():
+// I am start of this container (outer)
+//
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
Hello World!
+// This Is Text Node
+//
+//
+// I am end of this container (outer)
+
+// 6. node.before()
+let beforeDiv = document.createElement('div');
+beforeDiv.innerHTML = 'This is inserted before.
';
+container.before(beforeDiv);
+
+// Output after node.before():
+// I am start of this container (outer)
+//
+//
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
Hello World!
+// This Is Text Node
+//
+//
+// I am end of this container (outer)
+
+// 7. node.after()
+let afterDiv = document.createElement('div');
+afterDiv.innerHTML = 'This is inserted after.
';
+container.after(afterDiv);
+
+// Output after node.after():
+// I am start of this container (outer)
+//
+//
+//
+// I am start of this container (inner)
+//
I am the first element
+// I am end of this container (inner)
+//
Hello World!
+//
Hello World!
+// This Is Text Node
+//
+//
+//
+// I am end of this container (outer)
+
+// 8. node.replaceWith()
+let replaceDiv = document.createElement('div');
+replaceDiv.innerHTML = 'This is replacing the original container.
';
+container.replaceWith(replaceDiv);
+
+// Output after node.replaceWith():
+// I am start of this container (outer)
+//
+// This is replacing the original container.
+//
+// I am end of this container (outer)
+```
+
+### Explanation:
+
+1. **`innerHTML`**:
+ - Appends `Hello World! ` to the end of the `container` div's content.
+
+2. **`document.createElement()`**:
+ - Creates a new `div`, sets its inner HTML to `Hello World! `, and appends it to the `container` div. It also adds a class name `alert` to this new `div`.
+
+3. **`document.createTextNode()`**:
+ - Creates a text node with the content `This Is Text Node` and appends it to the `container` div.
+
+4. **`node.append()`**:
+ - Appends a new `div` containing a paragraph with the text `This is appended.` to the end of the `container` div's content.
+
+5. **`node.prepend()`**:
+ - Prepends a new `div` containing a paragraph with the text `This is prepended.` to the beginning of the `container` div's content.
+
+6. **`node.before()`**:
+ - Inserts a new `div` containing a paragraph with the text `This is inserted before.` before the `container` div.
+
+7. **`node.after()`**:
+ - Inserts a new `div` containing a paragraph with the text `This is inserted after.` after the `container` div.
+
+8. **`node.replaceWith()`**:
+ - Replaces the `container` div with a new `div` containing a paragraph with the text `This is replacing the original container.`
+
+By the end of the script execution, the DOM structure will be significantly modified as per the explained output comments.
+
+## Browser Events
+
+### Mouse Events
+1. `click` - Fired when an element is clicked.
+2. `dblclick` - Fired when an element is double-clicked.
+3. `mousedown` - Fired when a mouse button is pressed down on an element.
+4. `mouseup` - Fired when a mouse button is released over an element.
+5. `mousemove` - Fired when the mouse pointer is moving while it is over an element.
+6. `mouseover` - Fired when the mouse pointer is moved onto an element.
+7. `mouseout` - Fired when the mouse pointer is moved out of an element.
+8. `mouseenter` - Fired when the mouse pointer is moved onto an element (does not bubble).
+9. `mouseleave` - Fired when the mouse pointer is moved out of an element (does not bubble).
+10. `contextmenu` - Fired when the right mouse button is clicked (or a context menu key is pressed).
+
+### Keyboard Events
+1. `keydown` - Fired when a key is pressed down.
+2. `keyup` - Fired when a key is released.
+3. `keypress` - Fired when a key that produces a character value is pressed down.
+
+### Form Events
+1. `submit` - Fired when a form is submitted.
+2. `change` - Fired when an element's value changes (for ` `, `