├── Ch 1 Practice Set.js
├── Ch 1 Variable.js
├── Ch 10 Network Request And Storing Data.js
├── Ch 11 Object Oriented Programing.js
├── Ch 12 Advanced JavaScript.js
├── Ch 2 Expression & Conditional Statement Practice Set.js
├── Ch 2 Expression & Conditional Statement.js
├── Ch 3 Loops And Functions Practice Set.js
├── Ch 3 Loops And Functions.js
├── Ch 4 String Practice Set.js
├── Ch 4 String.js
├── Ch 5 Array Practice Set.js
├── Ch 5 Array.js
├── Ch 6 JS In Browser.js
├── Ch 6 JavaScript In Browser Practice Set.js
├── Ch 6 JavaScript In Browser.js
├── Ch 7 DOM Part 1.js
├── Ch 7 DOM Part 2.js
├── Ch 7 DOM Practice Set.js
├── Ch 7 Js DOM.js
├── Ch 8 Event & Other DOM Properties.js
├── Ch 8 Events And Other DOM Properties.js
├── Ch 9 Callbacks, Promises And Async And Await.js
├── Ch-10-Network-Request-And-Storing-Data.zip
├── Ch-10-Network-Request-And-Storing-Data
├── .gitignore
├── Readme.md
├── image.png
├── index.html
├── script.js
└── style.css
├── Ch-11-Object-Oriented-Programing.zip
├── Ch-11-Object-Oriented-Programing
├── .gitignore
├── Readme.md
├── image.png
├── index.html
├── script.js
└── style.css
├── Ch-12-Advanced-JavaScript.zip
├── Ch-12-Advanced-JavaScript
├── .gitignore
├── Readme.md
├── index.html
├── script.js
└── style.css
├── Ch-4-String.zip
├── Ch-4-String
├── Readme.md
└── index.js
├── Ch-6-JS-In-Browser.zip
├── Ch-6-JS-In-Browser
├── .gitignore
├── index.html
├── script.js
└── style.css
├── Ch-7-Js-DOM.zip
├── Ch-7-Js-DOM
├── .gitignore
├── Readme.md
├── image.png
├── index.html
├── script.js
└── style.css
├── Ch-8-Events-And-Other-DOM-Properties.zip
├── Ch-8-Events-And-Other-DOM-Properties
├── .gitignore
├── Readme.md
├── index.html
├── script.js
└── style.css
├── Ch-9-Callbacks-Promises-And-AsyncAwait.zip
├── Ch-9-Callbacks-Promises-And-AsyncAwait
├── .gitignore
├── Readme.md
├── image.png
├── index.html
├── script.js
└── style.css
└── README.md
/Ch 1 Practice Set.js:
--------------------------------------------------------------------------------
1 | //Ch 1 Variable -> Practice Set
2 |
3 | // Q1) Create a Variable of Type String And try To Add a Number To It.
4 |
5 |
6 | let a = "Darshan";
7 | let b = 10;
8 |
9 | console.log(a + b);
10 |
11 | // Output: Darshan10
12 |
13 |
14 | // Q2) Use typeof Operator To Find Data-type of the First Question of the Last Answer.
15 |
16 |
17 | console.log(typeof (a + b));
18 |
19 | // Output: String
20 |
21 |
22 | // Q3) Create a Const Object in JavaScript. Can You Change It to Hold A Number Latter?
23 |
24 |
25 | const c = {
26 | name: "Darshan",
27 | author: "CrptoMinds",
28 | isPrincipal: false
29 | }
30 |
31 | c = 1;
32 | // Output: Assignment to Constant Variable -> Ans Is No
33 |
34 |
35 | // Q4) Try To Add a New Key In Q3 Const Object. Were You Able To Do It?
36 |
37 |
38 | const c1 = {
39 | name: "Darshan",
40 | author: "CrptoMinds",
41 | isPrincipal: false
42 | }
43 |
44 | c1['friend'] = "Krupali";
45 |
46 | //const c1 -> Point Object -> We Can Change Value Inside The Object -> We Can't Make New c1 Objact Again -> Because Of Constant
47 | console.log(c1);
48 |
49 | // Output:
50 | // {
51 | // name: 'Darshan',
52 | // author: 'CrptoMinds',
53 | // isPrincipal: false,
54 | // friend: 'Krupali'
55 | // }
56 |
57 |
58 | // Q4) Write A JS Program To Create a Word-Meaning Dictionary Of 5 Words.
59 |
60 |
61 | const dict = {
62 | appreciate: "recognize the full worth of ",
63 | ataraxia: "a state of freedom from emotional disturbance",
64 | yakka: "Work, especially hard work."
65 |
66 | }
67 |
68 | console.log(dict.yakka);
69 | console.log(dict['yakka']);
70 |
71 | // Output: Work, especially hard work.
72 | // Work, especially hard work.
--------------------------------------------------------------------------------
/Ch 1 Variable.js:
--------------------------------------------------------------------------------
1 | // Variable Declaration:
2 | // To declare a variable in JavaScript:
3 | // Before ES6 -> var was used -> After ES6 -> let is used
4 | // const is used to define constant -> throughout the program value not changed
5 |
6 | // Let, Const -> Used To Block Scope Variable Declaration
7 | // Var -> Globally Scoped
8 | // Let Can Be Updated But Not Re-declared
9 | //Const -> Neither Updated Nor Re-declared
10 | // Var -> Can Be Updated And Re-declared
11 | // Var & Let Is Initialized With Undefined -> Const Are Not
12 | var dp;
13 | let ap;
14 | const hp; //Error
15 |
16 | var myVariable; // Declaration using var
17 | let anotherVariable; // Declaration using let
18 | const PI = 3.14159; // Declaration using const
19 |
20 | // JS is Case Sensitive
21 |
22 | // You can also declare and assign a value to a variable in a single line.
23 |
24 | //JavaScript Data-Type
25 | //Object Is Non Primitive Data-Type
26 | // Primitive -> Null, Number, String, Symbol, Undefined, Boolean, Bigint -> Fundamental Data-Type -> nn bb ss u
27 |
28 |
29 | let y = BigInt("265");
30 | let x = Symbol("I Am Symbol");
31 | let s = null; //Define Null
32 |
33 | // Type
34 | console.log(typeof x);
35 |
36 | //Object -> In Python -> Dictionary
37 | //ES6 -> ECMAScript -> Modern JavaScript
38 | const item = {
39 | name: "CryptoMinds",
40 | age: "12"
41 | //Key: Value
42 | }
43 |
44 | console.log(item["age"]); //Look Up
45 |
46 | //Scope -> Alt + Click -> Multiple Cursor In Replit
47 | //var
48 |
49 | var b = 11;
50 | var b = 13; // Allow To Use
51 |
52 | {
53 | var b = 15;
54 | console.log(b);
55 | }
56 | console.log(b);
57 |
58 | //Output
59 | // 15
60 | // 15
61 |
62 | //let
63 |
64 | let b = 11;
65 |
66 | {
67 | let b = 15;
68 | console.log(b);
69 | }
70 | console.log(b);
71 |
72 | //Output
73 | // 15
74 | // 11
75 |
76 |
77 | let c = 16;
78 | c = 17; //Update
79 |
80 |
81 | let d = 16;
82 | let d = 17; //Error
83 |
84 |
85 |
86 |
87 |
88 |
89 | var myNumber = 42;
90 | let myString = "JavaScript";
91 | const myConstant = true;
92 |
93 | // Variable Naming:
94 | // JavaScript variable names can include letters, digits, underscores, and dollar signs. They must start with a letter, underscore, or dollar sign (but not a digit). JavaScript is case-sensitive, so myVariable and myvariable are considered different variables.
95 |
96 | var firstName;
97 | let age;
98 | const PI = 3.14;
99 |
100 |
101 |
102 | // Better Practice to use let and Const
103 | // Mostly Use Const
104 | // JS Allow to Change Variable Type In Run Time -> Only One
105 |
106 |
107 | function myFunction() {
108 | var x = 10; // Function-scoped variable
109 | if (x > 5) {
110 | let y = 20; // Block-scoped variable
111 | console.log(x + y);
112 | }
113 | console.log(x); // Accessible
114 | console.log(y); // Error: y is not defined
115 | }
116 |
117 |
118 | // Variable Hoisting:
119 | // JavaScript has a concept called "hoisting," where variable and function declarations are moved to the top of their respective scopes during the compilation phase. Variables declared with var are hoisted but are not initialized until the line where they are defined. This can sometimes lead to unexpected behavior.
120 |
121 |
122 | console.log(x); // Undefined
123 | var x = 10;
124 |
125 |
126 | // Variable Constants:
127 | // Variables declared with const are constants, meaning their value cannot be reassigned once it is set. However, it's important to note that const does not make objects or arrays immutable. It only prevents the reassignment of the variable itself.
128 |
129 |
130 | const PI = 3.14;
131 | PI = 3.14159; // Error: Assignment To Constant Variable
132 |
133 | const myArray = [1, 2, 3];
134 | myArray.push(4); // Valid, Since The Array Itself Is Mutable
135 |
136 | // Conclusion:
137 | // JavaScript variables play a crucial role in storing and manipulating data within a program. By understanding variable declaration, assignment, naming, scope, and the differences between var, let, and const, developers can effectively work with variables to create dynamic and interactive JavaScript applications.
--------------------------------------------------------------------------------
/Ch 10 Network Request And Storing Data.js:
--------------------------------------------------------------------------------
1 | // Fetch API
2 | // The Fetch API provides a simple way to fetch resources (for example images, documents, or streams) over the internet
3 |
4 | // JavaScript Can Be Used To Send And Retrieve Information From The Network When Needed (AJAX)
5 |
6 | // AJAX Used Earlier -> Now JSON Is Widely Used
7 |
8 | // AJAX -> Asynchronous JavaScript And XML
9 |
10 | // Fetch API
11 |
12 | // Fetch Is Used To Get Data Over The Internet
13 |
14 | // let promise = fetch(URL, [options])
15 | // Without Option A GET Request Is Sent
16 |
17 | // Getting The Response Is A 2-Stage Process
18 |
19 | // 1. An Object Of Response Class Containing "Status" And "Ok" Properties
20 | // Status - The HTTP Status Code, eg 200
21 | // Ok - Boolean, True If The HTTP Status Code Is 200-299
22 |
23 | // 2. After That We Need To Call Another Method To Access The Body In Different Formats
24 |
25 | // Response.text() - Read The Response As Text
26 | // Response.json() - Parse The Response As JSON
27 |
28 | // Other Methods Include - Response.formData(), Response.blob(), Response.arrayBuffer()
29 |
30 | // Note - We Can Use Only One Body Method. For Example If We Have Used Response.text() Then We Cannot Use Response.json()
31 |
32 | // Response Headers
33 |
34 | // The Response Headers Are Available In Response.headers
35 |
36 | // Request Headers
37 | // To Set A Request Header In Fetch, We Can Use The Headers Option
38 |
39 | // let res = fetch(url, {
40 | // header: {
41 | // Authentication: 'Secret'
42 | // }
43 | // });
44 |
45 |
46 | // POST Request
47 |
48 | // let p = fetch("https://api.rainviewer.com/public/weather-maps.json")
49 | // p.then((response) => {
50 | // console.log(response.status)
51 | // console.log(response.ok)
52 | // console.log(response.headers)
53 | // return response.json()
54 | // }).then(data => {
55 | // console.log(data)
56 | // })
57 | // Why Two .then Is Mentioned Above?
58 | // Response Contain Two Properties - Status And Ok
59 | // Data Is The Actual Result Of The Request
60 |
61 | // POST Request
62 | // To Make Post Request, We Need To Use Fetch Options
63 | // Method -> HTTP Method, E.g POST
64 | // Body -> The Request Body
65 |
66 | // const createTodo = async (todo) => {
67 | // let options = {
68 | // method: "POST",
69 | // headers: {
70 | // "Content-type": "application/json"
71 | // },
72 | // body: JSON.stringify(todo),
73 | // }
74 | // let p = await fetch('https://jsonplaceholder.typicode.com/posts', options)
75 | // let response = await p.json()
76 | // return response
77 | // }
78 |
79 | // const getTodo = async (id) => {
80 | // let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id)
81 | // let r = await response.json()
82 | // return r
83 | // }
84 |
85 | // const mainFunc = async () => {
86 | // let todo = {
87 | // title: 'Harry2',
88 | // body: 'bhai2',
89 | // userId: 1100,
90 | // }
91 | // let todor = await createTodo(todo)
92 | // console.log(todor)
93 | // console.log(await getTodo(101))
94 | // }
95 |
96 | // mainFunc()
97 |
98 | // let response = await fetch('/url', {
99 | // method: 'POST',
100 | // headers: {
101 | // 'Content-Type': 'application/json'
102 | // },
103 | // body: JSON.stringify({
104 | // title: 'foo',
105 | // body: 'bar',
106 | // userId: 1,
107 | // })
108 | // })
109 |
110 | // let result = await response.json()
111 |
112 | // JavaScript Cookies
113 | // Cookies Are Small Strings Of Data Stored By The Client Side Stored In Browser
114 | // In JavaScript, Document.cookie Property Can Be Used To Access Cookies
115 |
116 | // 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.
117 |
118 | // We Can Also Access Cookies Using document.cookie Property
119 | // alert(document.cookie) -> Contain Key Value Pairs Decoded
120 |
121 | // Key Value Pair Are Separated By Delimited By ; -> Key = Pair;
122 |
123 | // Writing A Cookie
124 | // An Assignment To Document.cookie Is Treated Specially In A Way That Write Operation Doesn't Touch Other Cookie
125 |
126 | // document.cookie = "name=harry1122334400"
127 | // Updates Only Cookie Named User To Harry
128 |
129 | // Bahot Chota Sa Data Store Karneka Tarika
130 | // console.log(document.cookie)
131 | // document.cookie = "name=harry1122334400"
132 | // document.cookie = "name2=harry11223344002" // Set Call
133 | // document.cookie = "name=harry" // Old Is Updated
134 | // let key = prompt("enter your key")
135 | // let value = prompt("enter your value")
136 | // document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
137 | // console.log(document.cookie)
138 |
139 | // Encode URI Component -> This Function Encodes A Set Of Special Characters In A Way That The Component Can Be Decoded Using DecodeURI
140 |
141 | // This Function Helps Keep The Valid Formatting. It Is Used Like This
142 |
143 | // document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
144 |
145 | // This Way Spacial Character Are Encoded
146 |
147 | // Cookies Option
148 |
149 | // Cookies Have Several Options Which Can Be Provided After Key=Value To A Set Call Like This :
150 |
151 | // document.cookie = "user=harry;path=/a;expires=Tue,29 March 204"
152 | // path -> Which Domain The Cookie Will Be Available On
153 | // document.cookie = "user=harry;path=/a;expires=Tue,29 March 2041 12:00:33 GMT"
154 | // Set Only One Cookies With Path And Expires
155 | // document.cookies -> Can Set Only One Cookie At A Time Other Are Option
156 |
157 |
158 | // Path Option Makes The Cookie Available Only At The /a and /a/b ................ Path. -> Not Available At /b But Available At /a/b
159 | // Expires At -> Date When Cookie Will Be Expired. Time Stamp In GMT
160 |
161 | // Note :
162 | // 1. The Name And Value Pair After EncodeURI Component Can Be Up To 4KB
163 | // 2. Total No Of Cookies Per Domain Is Limited To Arbitrary Number Around 20+ (Exact Number Is Browser Dependent)
164 | // 3. Cookies Are Sent With Each Request To The Server, So The Server Can Learn Who Sent The Request
165 |
166 | // Local Storage
167 | // Local Storage Is Web Storage Object Which Are Not Sent To Server With Each Request
168 | // Data Survives Page Refresh And Even After Full Restart
169 |
170 | // These Are Method Provided By Local Storage
171 |
172 | // 1. localStorage.setItem(key, value) -> Store Key Value Pair Or Update The Value If Key Is Already Present
173 | // 2. localStorage.getItem(key) -> Get The Value By Key
174 | // 3. localStorage.removeItem(key) -> Remove The Key Value Pair
175 | // 4. localStorage.clear() -> Clear The Entire Local Storage
176 | // 5. localStorage.key(index) -> Get The Key On A Given Position
177 | // 6. localStorage.length -> The Number Of Stored Items
178 | // We Can Use Both Key And Value As String
179 |
180 | // let key = prompt("Enter key you want to set")
181 | // let value = prompt("Enter value you want to set")
182 |
183 | // localStorage.setItem(key, value)
184 |
185 | // console.log(`The value at ${key} is ${localStorage.getItem(key)}`)
186 |
187 | // if (key == "red" || key == "blue") {
188 | // localStorage.removeItem(key)
189 | // }
190 |
191 | // if (key == 0) {
192 | // localStorage.clear()
193 | // }
194 | // console.log(localStorage.length)
195 |
196 | // We Can Get And Set Values Like An Object
197 | // localStorage.one = 1
198 | // alert(localStorage.one)
199 | // delete localStorage.one
200 |
201 | // Note:
202 | // 1. Both Key And Value Must Be String
203 | // 2. We Can Use The Two JSON Methods To Store Objects In Local Storage
204 |
205 | // JSON.stringify(object) -> Converts Objects To JSON Strings
206 | // JSON.parse(string) -> Converts String To Objects (Must Be Valid JSON)
207 |
208 | // Session Storage
209 | // Session Storage Exists For Only One Session. Data Survives Refresh But Not Close Of Browser
210 |
211 | // Used Less As Compared To Local Storage
212 | // Properties And Method Are Same As Local Storage But:
213 | // 1. Session Storage Data Survives Page Refresh But Not Close Of Browser
214 | // It Exists Only Within The Current Browser Tab. Another Tab With Same Page Will Have Empty Session Storage
215 |
216 | // 2. The Data Survives Page Refresh, But Not Closing / Opening Of Browser
217 |
218 | // Storage Event
219 | // When The Data Gets Updated In Local Storage Or Session Storage, Storage Event Triggered With These Properties:
220 | // 1. key -> The Key
221 | // 2. oldValue -> Previous Value
222 | // 3. newValue -> New Value
223 | // 4. url -> Page URL
224 | // 5. storageArea -> local or session
225 |
226 | // We Can Listen The OnStorage Event Of Window Which Is Triggered When Updates Are Made To The Same Storage From Other Documents
227 |
228 | // sessionStorage.getItem("name")
229 | // sessionStorage.clear()
230 | // sessionStorage.removeItem("name")
231 | // sessionStorage.setItem("name", "harry")
232 | // sessionStorage.removeItem("name")
233 |
234 | // Dusri Tab Dusra Page Different Session Storage
235 |
236 | // window.onstorage = (e) => {
237 | // alert("changed")
238 | // console.log(e)
239 | // }
240 |
241 | // Practice Set
242 |
243 | // Q1 Use a Free API From The Internet And Feed Your App With Live Data
244 |
245 | // Q2 Create A Note Saving App Which Stores Your Note To localStorage
246 |
247 | // Q3 Repeat Q2 And Fetch The Note Which User Entered In The Previous Question
248 |
249 | // Q4 Delete The Note In The Previous Question
250 |
251 |
252 | let url = "https://kontests.net/api/v1/all"
253 | let response = fetch(url)
254 | response.then((v) => {
255 | return v.json()
256 | }).then((contests) => {
257 | console.log(contests)
258 | ihtml = ""
259 | for (item in contests) {
260 | console.log(contests[item])
261 | ihtml += `
262 |
263 |
264 |
265 |
${contests[item].name}
266 |
Status is ${contests[item].status} and site is ${contests[item].site}
267 |
In 24 Hours? ${contests[item].in_24_hours}
268 |
Starts at: ${contests[item].start_time}
269 |
Starts at: ${contests[item].end_time}
270 | Visit Contest
271 |
272 |
273 | `
274 | }
275 | cardContainer.innerHTML = ihtml
276 | })
277 |
278 | /* ******************* NOTES APP (REMAINING QUESTIONS OF PRACTICE SET) *********** */
279 | // let n = localStorage.getItem("note")
280 | // alert("Your note is " + n)
281 |
282 | // let a = prompt("Enter your note")
283 | // if (a) {
284 | // localStorage.setItem("note", a)
285 | // }
286 |
287 | // let c = confirm("Do you want to delete your note?")
288 | // if (c) {
289 | // localStorage.removeItem("note")
290 | // alert("Note deleted successfully!")
291 | // }
292 |
--------------------------------------------------------------------------------
/Ch 11 Object Oriented Programing.js:
--------------------------------------------------------------------------------
1 | // [[Prototype]]
2 | // First Priority Object Method Ki Than Nahi Mila To Prototype Ka Method Use Karo
3 | // JavaScript Object Have A Special Property Called Prototype That Is Either Null Or Reference To Another Object
4 |
5 | // 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.
6 |
7 | // let a = {
8 | // name2: "Harry",
9 | // language: "JavaScript",
10 | // run: () => {
11 | // alert("self run")
12 | // }
13 | // }
14 | // console.log(a)
15 |
16 |
17 | // let p = {
18 | // run: () => {
19 | // alert("run")
20 | // }
21 | // }
22 |
23 | // p.__proto__ = {
24 | // name: "Jackie"
25 | // }
26 |
27 | // a.__proto__ = p
28 | // a.run()
29 | // console.log(a.name)
30 |
31 | // Setting Prototype
32 | // 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
33 |
34 | // 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.
35 |
36 | // Classes And Objects
37 |
38 | // 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)
39 |
40 | // Syntax:
41 | // class ClassName {
42 | // constructor() {
43 | // // initialise
44 | // }
45 | // // Function
46 | // method_name() {
47 | // // code
48 | // }
49 | // }
50 |
51 | // class RailwayForm {
52 | // submit() {
53 | // alert(this.name + ": Your form is submitted for train number: " + this.trainno)
54 | // }
55 | // cancel() {
56 | // alert(this.name + ": This form is cancelled for train number: " + this.trainno)
57 | // }
58 | // fill(givenname, trainno) {
59 | // this.name = givenname
60 | // Object Associated Property = Input Me A Rahi Value
61 | // this.trainno = trainno
62 | // }
63 | // }
64 |
65 | // // Create a form for Harry
66 | // let harryForm = new RailwayForm()
67 | // // Fill the form with Harry's details
68 | // harryForm.fill("Harry", 145316)
69 |
70 | // // Create a forms for Rohan
71 | // let rohanForm1 = new RailwayForm()
72 | // let rohanForm2 = new RailwayForm()
73 | // // Fill the forms with Rohan's details
74 | // rohanForm1.fill("Rohan", 222420)
75 | // rohanForm2.fill("Rohan", 2229211)
76 |
77 | // harryForm.submit()
78 | // rohanForm1.submit()
79 | // rohanForm2.submit()
80 | // rohanForm1.cancel()
81 |
82 | // We Can Than Use New Class() To Create An Object
83 |
84 | // Constructor Method
85 | // A Constructor Is A Special Method Which Is Automatically Called When An Object Is Created. -> Its Used To Initialize The Object.
86 |
87 | // Old
88 |
89 | // class RailwayForm {
90 | // constructor(givenname, trainno) {
91 | // console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno)
92 | // this.name = givenname
93 | // this.trainno = trainno
94 | // }
95 |
96 | // submit() {
97 | // alert(this.name + ": Your form is submitted for train number: " + this.trainno)
98 | // }
99 | // cancel() {
100 | // alert(this.name + ": This form is cancelled for train number: " + this.trainno)
101 | // }
102 | // }
103 |
104 | // // Create & fill a form for Harry
105 | // let harryForm = new RailwayForm("Harry", 145316)
106 | // // No need to Fill the form with Harry's details
107 | // // harryForm.fill()
108 |
109 | // // Create & fill a forms for Rohan
110 | // let rohanForm1 = new RailwayForm("Rohan", 222420)
111 | // let rohanForm2 = new RailwayForm("Rohan", 2229211)
112 |
113 |
114 |
115 | // harryForm.submit()
116 | // rohanForm1.submit()
117 | // rohanForm2.submit()
118 | // rohanForm1.cancel()
119 |
120 | // New
121 |
122 | // class RailwayForm {
123 | // constructor(givenname, trainno, address) {
124 | // console.log("CONSTRUCTOR CALLED..." + givenname + " " + trainno)
125 | // this.name = givenname
126 | // this.trainno = trainno
127 | // this.address = address
128 | // }
129 |
130 | // preview() {
131 | // alert(this.name + ": Your form is for Train number: " + this.trainno + " and your address is " + this.address)
132 | // }
133 |
134 | // submit() {
135 | // alert(this.name + ": Your form is submitted for train number: " + this.trainno)
136 | // }
137 |
138 | // cancel() {
139 | // alert(this.name + ": This form is cancelled for train number: " + this.trainno)
140 | // this.trainno = 0
141 | // }
142 | // }
143 |
144 | // let harryForm = new RailwayForm("Harry", 13488, "420, Pacific Ocean, Ocean, Bihar - 0000555")
145 | // harryForm.preview()
146 | // harryForm.submit()
147 | // harryForm.cancel()
148 | // harryForm.preview()
149 |
150 |
151 | // Class Inheritance
152 |
153 | // 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.
154 |
155 | // class Animal {
156 | // constructor(name, color) {
157 | // this.name = name
158 | // this.color = color
159 | // }
160 | // run() {
161 | // console.log(this.name + " is running!")
162 | // }
163 | // shout() {
164 | // console.log(this.name + " is barking!")
165 | // }
166 | // }
167 |
168 | // class Monkey extends Animal {
169 | // eatBanana() {
170 | // console.log(this.name + " is eating banana")
171 | // }
172 | // hide() {
173 | // console.log(`${this.name} is hiding`)
174 | // }
175 | // }
176 |
177 | // let ani = new Animal("Bruno", "white")
178 | // let m = new Monkey("Chimpu", "orange")
179 |
180 | // ani.shout()
181 | // m.eatBanana()
182 | // m.hide()
183 | // // ani.hide() //This will throw an error
184 |
185 | // Extend Keyword
186 |
187 | // Extend Keyword Is Used To Extend Another Class.
188 |
189 |
190 | // Class Child extends Parent
191 |
192 | // Parent Classes Is The Class From Which Other Class Inherits.
193 | // class Animal {
194 | // constructor(name, color) {
195 | // this.name = name
196 | // this.color = color
197 | // }
198 | // run() {
199 | // console.log(this.name + " is running")
200 | // }
201 | // shout() {
202 | // console.log(this.name + " is shouting")
203 | // }
204 | // }
205 | // // Child Class
206 | // class Monkey extends Animal {
207 | // eatBanana() {
208 | // console.log(this.name + " is eating banana")
209 | // }
210 | // }
211 |
212 | // Method Overriding
213 | // Method Overriding Is A Feature In OOP Language Where A Child Class Can Override A Parent Method.
214 |
215 | // class Employee {
216 | // constructor(name) {
217 | // console.log(`${name} - Employee's constructor is here`)
218 | // this.name = name
219 | // }
220 | // login() {
221 | // console.log(`Employee has logged in`);
222 | // }
223 |
224 | // logout() {
225 | // console.log(`Employee has logged out`);
226 | // }
227 |
228 | // requestLeaves(leaves) {
229 | // console.log(`Employee has requested ${leaves} leaves - Auto approved`)
230 | // }
231 | // }
232 |
233 | // class Programmer extends Employee {
234 | // constructor(name) {
235 | // super(name)
236 | // console.log(`This is a newly written constructor`)
237 | // }
238 | // // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically
239 | // // super(...args)
240 | // // }
241 | // requestCoffee(x) {
242 | // console.log(`Employee has requested ${x} coffees`)
243 | // }
244 | // requestLeaves(leaves) {
245 | // super.requestLeaves(4)
246 | // console.log("One extra is granted")
247 | // // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`)
248 |
249 | // }
250 | // }
251 |
252 | // let e = new Programmer("Harry")
253 | // e.login()
254 | // e.requestLeaves(3)
255 |
256 | // If We Create Our Own Implimentstion Of Run Method In Child Class, It Will Be Overridden.
257 |
258 | // Super Kewword
259 | // Super Keyword Is Used To Call The Parent Class Constructor.
260 | // When We Override A Method In Child Class, We Use Super Keyword To Call The Parent Class Method.
261 |
262 | // super(a,b) -> Call Parent Class Constructor
263 |
264 |
265 | // Overriding Constructor
266 |
267 | // 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.
268 |
269 | // Default One
270 | // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically
271 | // // super(...args)
272 | // // }
273 |
274 | // Constructor In Inheriting Classes Mus Call Super (...) And Do It Before Using This.
275 | // We Can Also Use super.method() In Child Class To Call Parent Class Method.
276 |
277 | // class Employee {
278 | // constructor(name) {
279 | // console.log(`${name} - Employee's constructor is here`)
280 | // this.name = name
281 | // }
282 | // login() {
283 | // console.log(`Employee has logged in`);
284 | // }
285 |
286 | // logout() {
287 | // console.log(`Employee has logged out`);
288 | // }
289 |
290 | // requestLeaves(leaves) {
291 | // console.log(`Employee has requested ${leaves} leaves - Auto approved`)
292 | // }
293 | // }
294 |
295 | // class Programmer extends Employee {
296 | // constructor(name) {
297 | // super(name)
298 | // console.log(`This is a newly written constructor`)
299 | // }
300 | // // constructor(...args){ ---> If there is no constructor in the child class, this is created automatically
301 | // // super(...args)
302 | // // }
303 | // requestCoffee(x) {
304 | // console.log(`Employee has requested ${x} coffees`)
305 | // }
306 | // requestLeaves(leaves) {
307 | // super.requestLeaves(4)
308 | // console.log("One extra is granted")
309 | // // console.log(`Employee has requested ${leaves + 1} leaves (One extra)`)
310 |
311 | // }
312 | // }
313 |
314 | // let e = new Programmer("Harry")
315 | // e.login()
316 | // e.requestLeaves(3)
317 |
318 |
319 | // Static Methods
320 | // Static Methods Are Methods Which Are Associated With A Class And Not With Any Instance Of It.
321 |
322 | // Static Method Are Used To Implement Logic Which Does Not Rely On Instance.
323 |
324 | // Static Method Are Used To Implement Function That Belong To A Class As A Whole. And Not To Any Particular Object.
325 |
326 | // We Can Assign Single Static Method;
327 |
328 | // Syntax:
329 |
330 | // class follow {
331 | // static method() {
332 | // console.log("This is a static method")
333 | // }
334 | // }
335 |
336 | // follow.method()
337 |
338 | // Static Methods Aren't Available For Individual Object
339 |
340 | // class Animal {
341 | // constructor(name) {
342 | // this.name = Animal.capitalize(name)
343 | // }
344 | // walk() {
345 | // alert("Animal " + this.name + " is walking")
346 | // }
347 | // static capitalize(name) {
348 | // return name.charAt(0).toUpperCase() + name.substr(1, name.length)
349 | // }
350 | // }
351 |
352 | // j = new Animal("jack")
353 | // j.walk()
354 | // console.log(j.capitalize("thisa")) // --- > this doesnt work
355 |
356 | // Getters And Setters
357 |
358 | // Getters And Setters Are Special Methods Which Are Used To Get And Set The Values Of An Object's Properties.
359 |
360 | // class Person {
361 | // constructor(name) {
362 | // this.name = name
363 | // }
364 | // fly() {
365 | // console.log("I am flying")
366 | // }
367 | // get name() {
368 | // return this._name
369 | // }
370 | // set name(newName) {
371 | // this._name = newName
372 | // }
373 | // }
374 |
375 | // class Animal {
376 | // constructor(name) {
377 | // this._name = name
378 | // }
379 | // fly() {
380 | // console.log("Mai ud rha hu")
381 | // }
382 | // get name() {
383 | // return this._name
384 | // }
385 |
386 | // set name(newName) {
387 | // this._name = newName
388 | // }
389 |
390 | // }
391 |
392 | // class Rabbit extends Animal {
393 | // eatCarrot() {
394 | // console.log("Eating carrot")
395 | // }
396 | // }
397 |
398 | // let a = new Rabbit("Bruno")
399 | // a.fly()
400 | // console.log(a.name)
401 | // a.name = "Jack"
402 | // console.log(a.name)
403 | // let c = 56
404 |
405 | // console.log(a instanceof Animal)
406 | // console.log(a instanceof Rabbit)
407 | // console.log(c instanceof Animal)
408 |
409 |
410 | // InstanceOf Operator
411 | // InstanceOf Operator Is Used To Check If An Object Is An Instance Of A Class.
412 | // Object It Belongs To Certain Class Or Not?
413 | // It Return True If Obj Belongs To The Class Or Any Other Class Inherited From It.
414 | // Syntax:
415 |
416 | // instanceof
417 |
418 | // Practice Set
419 |
420 | // Q1 Create A Class To Create A Complex Number. Create A Constructor To Set The Real And Imaginary Parts.
421 |
422 | // Q2 Write A Method To Add Two Complex Numbers In The Above Class.
423 |
424 | // Q3 Create A Class Student From A Class Human. Override A Method And See Changes.
425 |
426 | // Q4 See If Student Is An Instance Of Human Using InstanceOf Keyword.
427 |
428 | // Q5 Use Getters And Setters To Set And Get The Real And Imaginary Parts Of The Complex Number.
429 |
430 |
431 | // class Complex {
432 | // constructor(real, imaginary) {
433 | // this.real = real
434 | // this.imaginary = imaginary
435 | // }
436 | // add(num) {
437 | // this.real = this.real + num.real
438 | // this.imaginary = this.imaginary + num.imaginary
439 |
440 | // }
441 |
442 | // get real() {
443 | // return this._real
444 | // }
445 |
446 | // get imaginary() {
447 | // return this._imaginary
448 | // }
449 |
450 | // set imaginary(newImaginary) {
451 | // this._imaginary = newImaginary
452 | // }
453 |
454 | // set real(newReal) {
455 | // this._real = newReal
456 | // }
457 | // }
458 |
459 | // let a = new Complex(2, 4)
460 | // console.log(a.real, a.imaginary)
461 | // a.real = 10
462 | // a.imaginary = 10
463 | // let b = new Complex(6, 2)
464 | // a.add(b)
465 | // console.log(`${a.real}+${a.imaginary}i`)
466 |
467 | // class Human {
468 | // constructor(name, favfood) {
469 | // this.name = name
470 | // this.favfood = favfood
471 | // }
472 | // walk() {
473 | // console.log(this.name + "Human is walking")
474 | // }
475 | // }
476 |
477 | // class Student extends Human {
478 | // walk() {
479 | // console.log(this.name + ": Student is walking")
480 | // }
481 | // }
482 |
483 | // let o = new Student("Harry", "Bhindi")
484 | // o.walk()
485 |
486 | // console.log(o instanceof Human)
--------------------------------------------------------------------------------
/Ch 12 Advanced JavaScript.js:
--------------------------------------------------------------------------------
1 | // IIFE -> Immediately Invoked Function Expression
2 |
3 | // IIFE Is A JavaScript Function That Runs As Soon As It Is Defined
4 | // (function() {
5 | // console.log("IIFE");
6 | // })();
7 |
8 | // // It is used to avoid polluting the global namespace, execute an async-await, etc.
9 |
10 | // let a = () => {
11 | // return new Promise((resolve, reject) => {
12 | // setTimeout(() => {
13 | // resolve(456)
14 | // }, 4000)
15 | // })
16 | // }
17 |
18 | // (async () => {
19 | // let b = await a()
20 | // console.log(b)
21 | // let c = await a()
22 | // console.log(c)
23 | // let d = await a()
24 | // console.log(d)
25 | // })()
26 |
27 |
28 | // console.log(d) // Throws error
29 |
30 | // Destructuring And Spread Operator
31 | // Destructuring Assignment Is Used To Unpack Values From An Array, Or Properties From An Object, Into Dedicated Variables, In JavaScript.
32 |
33 | // let arr = [3, 5, 8, 9, 12, 14]
34 | // No need to do this:
35 | // let a = arr[0]
36 | // let b = arr[1]
37 | // let [a, b, c, d, ...rest] = arr
38 | // console.log(a, b, c, d, rest)
39 | // let [a, , b, ...rest] = arr
40 | // console.log(a, b, rest)
41 | // let { a, b } = { a: 1, b: 5 }
42 | // console.log(a, b)
43 |
44 | // [10, x,....rest] =[10, 20, 30, 40, 50, 60]
45 | // x will be 20 rest will be [30, 40, 50, 60]
46 |
47 | // Spread Operator
48 |
49 | // 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)
50 | // let arr1 = [3, 5, 8]
51 | // let obj1 = { ...arr1 }
52 | // console.log(obj1)
53 |
54 | // function sum(v1, v2, v3) {
55 | // return v1 + v2 + v3
56 | // }
57 |
58 | // console.log(sum(...arr1))
59 |
60 | // let obj2 = {
61 | // name: "Harry",
62 | // company: "Company xyz",
63 | // address: "XYZ"
64 | // }
65 |
66 | // console.log({ ...obj2, name: "John", company: "ABC" })
67 | // console.log({ name: "John", company: "ABC", ...obj2 }) // This will print the obj2 object without changing any values
68 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
69 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
70 |
71 | // Local, Global And Function Scope In JavaScript
72 | // var -> Global Scope
73 | // let and const -> Block Scope
74 | // Function Scope -> The variable declared inside a function, becomes local to the function.
75 |
76 | // let p = 9
77 | // function ax() {
78 | // let a = 8;
79 | // console.log(p)
80 | // console.log(a)
81 | // }
82 |
83 | // ax()
84 | // console.log(p)
85 | // console.log(a)
86 |
87 |
88 | // Hoisting In JavaScript
89 | // Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution
90 |
91 | // let a;
92 | // Following two lines will run successfully due to JavaScript hoisting
93 | // console.log(a)
94 | // greet()
95 | // var greet = function() {
96 | // console.log("Good morning")
97 | // }
98 |
99 | // var a = 9; // Declaration hoisted to the top but initialization is not
100 | // console.log(a)
101 |
102 | // Hoisting With Let And Var
103 | // let and const are not hoisted
104 | // console.log(num);
105 | // let num = 6; -> Throws an error
106 | // var num = 6; -> Doesn't throw an error
107 | // const num = 6; -> Throws an error
108 |
109 | // Function Expression And Class Expression Are Not Hoisted
110 | // Function Expression Me = Sign Ata He
111 |
112 | // Closer Set
113 |
114 | // A Closer Is A Function With Lexical Environment
115 |
116 | // function init() {
117 | // var name = 'Mozilla'; // name is a local variable created by init
118 | // function displayName() {
119 | // // displayName() is the inner function, a closure
120 | // console.log(name); // use variable declared in the parent function
121 | // }
122 | // name = "Harry"
123 | // return displayName;
124 | // }
125 | // let c = init();
126 | // c()
127 |
128 |
129 | // function returnFunc() {
130 | // const x = () => {
131 | // let a = 1
132 | // console.log(a)
133 | // const y = () => {
134 | // // let a = 2
135 | // console.log(a)
136 | // const z = () => {
137 | // // let a = 3
138 | // console.log(a)
139 | // }
140 | // z()
141 | // }
142 | // a = 999
143 | // y()
144 | // }
145 | // return x
146 | // }
147 |
148 | // let a = returnFunc()
149 | // a()
150 |
151 | // Closure -> Function + Its Lexical Environment
152 | // Reference Milta He
153 |
154 | // Lexical Environment -> The Environment Of The Function -> Mere Pass Nahi He To Mere Pass Ka Environment Me Ase Check Karega
155 |
156 | // Arrow Function
157 |
158 | // const sayHello = name => {
159 | // console.log("greeting" + " " + name)
160 | // console.log("hi")
161 | // }
162 |
163 | // const x = {
164 | // name: "Harry",
165 | // role: "Js Developer",
166 | // exp: 30,
167 | // show: function() {
168 | // // let that = this
169 | // // console.log(this)
170 | // setTimeout(() => {
171 | // // console.log(`The name is ${that.name}\nThe role is ${that.role}`)
172 | // console.log(`The name is ${this.name}\nThe role is ${this.role}`)
173 | // }, 2000)
174 | // }
175 | // }
176 | // sayHello("Harry", "Good Afternoon")
177 | // console.log(x.name, x.exp)
178 | // x.show()
179 |
180 | // Arrow Function Uses Lexical This
181 |
182 | // Practice Set
183 |
184 | // const a = async (text, n = 2) => {
185 | // return new Promise((resolve, reject) => {
186 | // setTimeout(() => {
187 | // resolve(text)
188 | // }, 1000 * n)
189 | // })
190 | // }
191 |
192 | // (
193 | // async () => {
194 | // let text = await a("Hello")
195 | // console.log(text)
196 | // text = await a("World")
197 | // console.log(text)
198 | // }
199 | // )()
200 |
201 | // function sum(a, b, c) {
202 | // return a + b + c
203 | // }
204 |
205 | // let x = [1, 3, 5]
206 | // console.log(sum(...x));
207 |
208 | // (async () => {
209 | // let text = await a("I am resolving after 1 second", 1)
210 | // console.log(text)
211 | // text = await a("I am resolving after 4 seconds", 4)
212 | // console.log(text)
213 | // }
214 | // )()
215 |
216 | // function simpleInterest(p, r, t) {
217 | // return (p * r * t) / 100;
218 | // }
219 |
220 | // console.log(simpleInterest(100, 5, 1))
221 |
222 | // Regex Expression Or Regular Expression
223 | // https://regexr.com/
224 | // const regex = /(Harry){2}/gi
225 | // const text = "Harryharry is a very very nice awesome nice very boy"
226 | // console.log(text.replace(regex, "VERY"))
227 |
228 | // Event Loop
229 |
230 | // Asynchronous CallBack
231 | // Sometimes the JavaScript code can take a lot of time and this can block the
232 | // page re render
233 | // JavaScript has asynchronous callbacks for non blocking behavior
234 | // JavaScript runtime can do only one thing at a time
235 | // Browser gives us other things which work along with the runtime like Web
236 | // APIs.
237 | // In node.js these are available as C++ APIs
238 |
239 | // setTimeout(function timer() {
240 | // console.log('You clicked the button!');
241 | // }, 2000);
242 |
243 | // console.log("Hi!");
244 |
245 | // setTimeout(function timeout() {
246 | // console.log("Click the button!");
247 | // }, 5000);
248 |
249 | // console.log("Welcome to loupe.");
250 |
251 | // Task Queue
252 | // JavaScript can do only one thing at a time
253 | // The rest are queued to the task queue waiting to be executed
254 | // When we run setTimeout, webapis will run a timer and push the function
255 | // provided to setTimeout to the task queue once the timer evis
256 | // These tasks will be pushed to the stack where they can executed
257 |
258 | // Event Loop
259 |
260 | // JavaScript has a runtime model based on an event loop, which is responsible
261 | // for executing the code, collecting and processing events, and executing queued
262 | // sub-tasks
263 | // The event loop pushes the tasks from the task queue to the call stack
264 | // setTimeout(func1, 0) can be used to defer a function until all the pending tasks
265 | // (so far) have been executed
266 | // We can see how these things work in action by visiting
267 | // For Understanding Call Stack In Js :http://latentflip.com/loupe/
268 |
269 | // Module In JS
270 |
271 |
272 | // const hello = ()=>{
273 | // console.log("Hello Harry")
274 | // }
275 |
276 | // const ahello = (name)=>{
277 | // console.log("Hello " + name)
278 | // }
279 |
280 | // module.exports = {hello, ahello};// same as below line
281 | // // module.exports = {hello: hello, ahello: ahello};
282 |
283 | // // ES6 Modules
284 | // export const hello = ()=>{
285 | // console.log("Hello Harry")
286 | // }
287 |
288 | // export const ahello = (name)=>{
289 | // console.log("Hello " + name)
290 | // }
291 |
292 | // const harry = ()=>{
293 | // console.log("Hello " + "Harry")
294 | // }
295 |
296 | // export default harry;
297 |
--------------------------------------------------------------------------------
/Ch 2 Expression & Conditional Statement Practice Set.js:
--------------------------------------------------------------------------------
1 | // Ch 2 Expression & Conditional Statement Practice Set
2 |
3 |
4 | // Q1) Use Logical Operator To Find Whether The Age Of a Person Lies Between 10 & 20.
5 |
6 | let age = 15;
7 |
8 | if (age >= 10 && age <= 20) {
9 | console.log("The age is between 10 and 20.");
10 | } else {
11 | console.log("The age is not between 10 and 20.");
12 | }
13 |
14 |
15 | // Q2) Demonstrate The Use Of Switch Statement In JS With an Example.
16 |
17 | let day = 3;
18 | let dayName;
19 |
20 | switch (day) {
21 | case 1:
22 | dayName = "Monday";
23 | break;
24 | case 2:
25 | dayName = "Tuesday";
26 | break;
27 | case 3:
28 | dayName = "Wednesday";
29 | break;
30 | case 4:
31 | dayName = "Thursday";
32 | break;
33 | case 5:
34 | dayName = "Friday";
35 | break;
36 | case 6:
37 | dayName = "Saturday";
38 | break;
39 | case 7:
40 | dayName = "Sunday";
41 | break;
42 | default:
43 | dayName = "Invalid day";
44 | }
45 |
46 | console.log(dayName);
47 |
48 |
49 | // Q3) Write JS Program To Find Whether the Number Is Divisible By 2 And 3.
50 |
51 | let number = 12;
52 |
53 | if (number % 2 === 0 && number % 3 === 0) {
54 | console.log(number + " is divisible by both 2 and 3.");
55 | } else {
56 | console.log(number + " is not divisible by both 2 and 3.");
57 | }
58 |
59 |
60 | // Q4) Print "You Can Drive" Or "You Can't Drive" Based On Age Being Greater Than 18 Using Ternary Operator
61 |
62 | let age = 20;
63 | let canDrive = age > 18 ? "You can drive." : "You can't drive.";
64 |
65 | console.log(canDrive);
66 |
67 |
68 |
--------------------------------------------------------------------------------
/Ch 2 Expression & Conditional Statement.js:
--------------------------------------------------------------------------------
1 | // Arithmetic Operators
2 | // + Addition
3 | // - Subtraction
4 | // * Multiplication
5 | // ** Exponential
6 | // / Division
7 | // % Modulus
8 | // ++ Increment
9 | // -- Decrement
10 |
11 | // -> Example
12 | // Arithmetic Operators
13 |
14 | let addition = 5 + 2; // 7
15 | let subtraction = 8 - 3; // 5
16 | let multiplication = 4 * 3; // 12
17 | let exponentiation = 2 ** 4; // 16
18 | let division = 10 / 2; // 5
19 | let modulus = 9 % 2; // 1
20 | let increment = 5;
21 | increment++; // 6
22 | let decrement = 10;
23 | decrement--; // 9
24 |
25 |
26 | // Assignment Operators
27 | // = X = Y
28 | // += X = X + Y
29 | // -= X = X - Y
30 | // *= X = X * Y
31 | // /= X = X / Y
32 | // %= X = X % Y
33 | // **= X = X ** Y
34 |
35 | // -> Example
36 | // Assignment Operators
37 | let x = 5;
38 | x += 3; // equivalent to x = x + 3
39 | x -= 2; // equivalent to x = x - 2
40 | x *= 4; // equivalent to x = x * 4
41 | x /= 2; // equivalent to x = x / 2
42 | x %= 3; // equivalent to x = x % 3
43 | x **= 2; // equivalent to x = x ** 2
44 |
45 |
46 | // Comparison Operators
47 | // == Equal To
48 | // != Not Equal To
49 | // === Equal Value And Type
50 | // !== Not Equal Value Or Type
51 | // > Greater Than
52 | // < Less Than
53 | // >= Greater Than Or Equal To
54 | // <= Less Than Or Equal To
55 | // ? Ternary Operator
56 |
57 | // -> Example
58 | // Comparison Operators
59 | let isEqual = (5 == 5); // true
60 | let isNotEqual = (5 != 3); // true
61 | let isEqualValueAndType = (5 === '5'); // false
62 | let isNotEqualValueOrType = (5 !== '5'); // true
63 | let isGreaterThan = (10 > 5); // true
64 | let isLessThan = (3 < 7); // true
65 | let isGreaterThanOrEqual = (8 >= 8); // true
66 | let isLessThanOrEqual = (4 <= 2); // false
67 |
68 |
69 | // Logical Operators
70 | // && Logical And
71 | // || Logical Or
72 | // ! Logical Not
73 |
74 | // -> Example
75 | // Logical Operators
76 | let logicalAnd = (true && false); // false
77 | let logicalOr = (true || false); // true
78 | let logicalNot = !true; // false
79 |
80 |
81 |
82 | // Bitwise Operators
83 | // Bitwise AND (&): Performs a bitwise AND operation on each pair of corresponding bits. The result is 1 if both bits are 1; otherwise, it is 0.
84 |
85 | // Bitwise OR (|): Performs a bitwise OR operation on each pair of corresponding bits. The result is 1 if at least one of the bits is 1; otherwise, it is 0.
86 |
87 | // Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits. The result is 1 if the bits are different; otherwise, it is 0.
88 |
89 | // Bitwise NOT (~): Flips the bits of a number. It converts each 0 to 1 and each 1 to 0.
90 |
91 | // Left Shift (<<): Shifts the bits of a number to the left by a specified number of positions. This operation effectively multiplies the number by 2 to the power of the specified shift amount.
92 |
93 | // Right Shift (>>): Shifts the bits of a number to the right by a specified number of positions. This operation effectively divides the number by 2 to the power of the specified shift amount.
94 |
95 | // Zero-fill Right Shift (>>>): Similar to the right shift operator (>>), but it always fills in the shifted positions with zeros. This is known as the zero-fill right shift.
96 |
97 | // Bitwise operators are commonly used in JavaScript for low-level manipulation of binary data, creating flags, and optimizing certain calculations. However, they are not frequently used in general-purpose programming and should be used judiciously due to their complexity and potential for confusion.
98 |
99 | // It's important to note that JavaScript treats numeric values as 32-bit signed integers when performing bitwise operations. To perform bitwise operations on larger numbers, consider using additional techniques or external libraries.
100 |
101 | // I hope these notes help you understand the basics of bitwise operators in JavaScript!
102 |
103 | // -> Example
104 | // Bitwise Operators
105 | let bitwiseAND = 5 & 3; // 1
106 | let bitwiseOR = 5 | 3; // 7
107 | let bitwiseXOR = 5 ^ 3; // 6
108 | let bitwiseNOT = ~5; // -6
109 | let leftShift = 5 << 2; // 20
110 | let rightShift = 5 >> 1; // 2
111 | let zeroFillRightShift = 5 >>> 1; // 2
112 |
113 |
114 | // Comments
115 |
116 | // Single Line Comment
117 |
118 | /* Multi Line Comment */
119 |
120 |
121 | // Conditional Statement
122 | // 3 Types Of Conditional Statement Are Available
123 | // If Statement
124 | // If....Else Statement
125 | // If....Else If....Else Statement
126 |
127 | // If Statement
128 |
129 | // if(condition){
130 | // //Execute This Code
131 | // } -> Execute Till Condition True
132 |
133 | // -> Example
134 | let x = 10;
135 |
136 | if (x > 5) {
137 | console.log("x is greater than 5"); // This block will be executed since the condition is true
138 | }
139 |
140 |
141 |
142 | // If....Else Statement
143 |
144 | // if(condition){
145 | // //Execute This Code If Condition Is True
146 | // }
147 | // else {
148 | // //Execute This Code If Condition Is False
149 | // }
150 |
151 | // -> Example
152 |
153 | let age = 18;
154 |
155 | if (age >= 18) {
156 | console.log("You are eligible to vote."); // This block will be executed since the condition is true
157 | } else {
158 | console.log("You are not eligible to vote."); // This block will be executed if the condition is false
159 | }
160 |
161 |
162 |
163 | // If....Else If Statement
164 | // -> Sometime We Required To Check Condition Again And Again.
165 |
166 | // if (condition1) {
167 | // // Code To Be Executed If Condition1 Is True
168 | // } else if (condition2) {
169 | // // Code To Be Executed If Condition2 Is True
170 | // } else {
171 | // // Code To Be Executed If All Conditions Are False
172 | // }
173 |
174 | // -> Example
175 |
176 | let num = 5;
177 |
178 | if (num > 0) {
179 | console.log("Number is positive.");
180 | } else if (num < 0) {
181 | console.log("Number is negative.");
182 | } else {
183 | console.log("Number is zero.");
184 | }
185 |
186 |
187 | // JavaScript Ternary Operator
188 |
189 | // The ternary operator, also known as the conditional operator, provides a concise way to write conditional expressions in JavaScript.
190 |
191 | // It is represented by the syntax: condition ? expression1 : expression2. -> True : False
192 |
193 | // The condition is evaluated first, and if it is true, expression1 is executed. If the condition is false, expression2 is executed.
194 |
195 | // -> Usage and Benefits:
196 |
197 | // The ternary operator is often used as a shorthand alternative to if...else statements when there are simple conditions and expressions involved.
198 |
199 | // It makes the code more concise and readable, especially for shorter conditional statements.
200 |
201 | // It can be used to assign a value to a variable based on a condition without the need for a separate if statement.
202 |
203 | // Examples:
204 |
205 | // Assigning a value based on a condition:
206 |
207 |
208 | let dp = 18;
209 | let message = (dp >= 18) ? "You are an adult" : "You are not an adult";
210 |
211 |
212 |
213 | // Returning a value from a function based on a condition:
214 |
215 | function checkEvenOrOdd(num) {
216 | return (num % 2 === 0) ? "Even" : "Odd";
217 | }
218 |
219 |
220 | // Nesting ternary operators (though it's recommended to keep it simple for readability):
221 |
222 | let nums = 10;
223 | let result = (nums > 0) ? "Positive" : (nums < 0) ? "Negative" : "Zero";
224 |
225 |
226 | // While the ternary operator can make code more concise, it should be used judiciously to maintain code readability. Complex conditions or expressions may be better suited for if...else statements.
227 |
228 | // Avoid nesting too many ternary operators, as it can make the code harder to understand and maintain.
229 |
230 | // Use appropriate spacing and formatting to enhance the readability of ternary expressions.
231 |
232 | // Remember, a ternary operator is a powerful tool for writing conditional expressions in a concise manner. However, it's important to strike a balance between readability and simplicity when using it in your JavaScript code.
233 |
234 |
235 | // Prefix Increment:
236 |
237 | let x = 5;
238 | let result = ++x; // Increment x by 1 and assign the new value to result
239 | console.log(result); // Output: 6
240 | console.log(x); // Output: 6
241 |
242 | // Postfix Increment:
243 |
244 | let y = 5;
245 | let result = y++; // Assign the current value of y to result, then increment y by 1
246 | console.log(result); // Output: 5
247 | console.log(y); // Output: 6
248 |
--------------------------------------------------------------------------------
/Ch 3 Loops And Functions Practice Set.js:
--------------------------------------------------------------------------------
1 | // Q1) Write A Program To Print Marks Of Student In An Object Using For Loop
2 | const marks = {
3 | dp: 100,
4 | ap: 99,
5 | hp: 98
6 | };
7 |
8 | for (let student in marks) {
9 | console.log(`${student}: ${marks[student]}`);
10 | }
11 |
12 | // Output
13 | // dp: 100
14 | // ap: 99
15 | // hp: 98
16 |
17 | // Q2) Write A Program In Q1 Using Using For In Loop
18 | const marks = {
19 | dp: 100,
20 | ap: 99,
21 | hp: 98
22 | };
23 |
24 | for (let student in marks) {
25 | console.log(`${student}: ${marks[student]}`);
26 | }
27 |
28 | // Output
29 | // dp: 100
30 | // ap: 99
31 | // hp: 98
32 |
33 |
34 | // Q3) Write A Program To Print "Try Again" Until The User Enter The Correct Number
35 |
36 | let correctNumber = 7;
37 | let userNumber;
38 |
39 | do {
40 | userNumber = parseInt(prompt('Enter a number:'));
41 | if (userNumber !== correctNumber) {
42 | console.log('Try again');
43 | }
44 | } while (userNumber !== correctNumber);
45 |
46 | // This program will keep prompting the user to enter a number until they enter the correct number (in this case, 7).
47 |
48 | // Q4) Write A Function To Find the Mean Of 5 Numbers
49 |
50 | function findMean(num1, num2, num3, num4, num5) {
51 | const sum = num1 + num2 + num3 + num4 + num5;
52 | const mean = sum / 5;
53 | return mean;
54 | }
55 |
56 | const result = findMean(10, 20, 30, 40, 50);
57 | console.log('Mean:', result);
58 |
59 | // Output
60 |
61 | // Mean: 30
62 |
63 | // Q5)Write a function named multiplyByTwo that takes a number as an argument and returns the result of multiplying that number by 2.
64 |
65 | function multiplyByTwo(num) {
66 | return num * 2;
67 | }
68 |
69 | // Q6)Write a function named reverseString that takes a string as an argument and returns the reverse of that string.
70 |
71 | function reverseString(str) {
72 | return str.split('').reverse().join('');
73 | }
74 |
75 | // Q7)Write a function named printEvenNumbers that takes a number as an argument and prints all the even numbers from 0 to that number.
76 |
77 | function printEvenNumbers(num) {
78 | for (let i = 0; i <= num; i++) {
79 | if (i % 2 === 0) {
80 | console.log(i);
81 | }
82 | }
83 | }
84 |
85 | // Q8) Write a function named calculateFactorial that takes a number as an argument and returns the factorial of that number.
86 |
87 | function calculateFactorial(num) {
88 | if (num === 0 || num === 1) {
89 | return 1;
90 | }
91 |
92 | let factorial = 1;
93 | for (let i = 2; i <= num; i++) {
94 | factorial *= i;
95 | }
96 |
97 | return factorial;
98 | }
99 |
100 | // Q9) Write a function named countOccurrences that takes an array of numbers and a target number as arguments and returns the number of times the target number appears in the array.
101 |
102 | function countOccurrences(arr, target) {
103 | let count = 0;
104 | for (let num of arr) {
105 | if (num === target) {
106 | count++;
107 | }
108 | }
109 | return count;
110 | }
111 |
112 | // Q10) What is an arrow function in JavaScript?
113 |
114 | // An arrow function is a shorter syntax for writing function expressions. It uses the => arrow token and does not bind its own this value. It is often used for writing concise and inline functions.
--------------------------------------------------------------------------------
/Ch 3 Loops And Functions.js:
--------------------------------------------------------------------------------
1 | // Loops & Functions
2 | // Loops and functions are essential concepts in JavaScript programming that help to create efficient and reusable code.
3 |
4 |
5 | // Types Of Loops
6 | //For Loop -> Loop a Block Of Code No Of Time
7 | //For In Loop -> Loop Through The Key Of An Object
8 | //For Of Loop -> Loop Through The Value Of An Object
9 | //While Loop -> Loop Of Block Based On Specific Condition
10 | // Do...While Loop -> While Loop Variant Which Run a At Least Once
11 |
12 |
13 | // For Loop
14 | // Syntax
15 | // for(Statement1;Statement2;Statement3){
16 | // // Code To Be Executed
17 | // }
18 | // Statement1 -> Executed One Time
19 | // Statement2 -> Condition Based -> Based On This Loop Body Will Be Executed
20 | // Statement3 -> Executed Every Time The Loop Body Is Executed
21 |
22 |
23 | // Example
24 | for (let i = 0; i < 5; i++) {
25 | console.log(i); // prints numbers from 0 to 4
26 | }
27 |
28 |
29 | // For In Loop
30 | //Loop Through The Key Of An Object
31 | // For In Loop Works With Array Also
32 |
33 | // Example
34 | const person = {
35 | name: 'John',
36 | age: 30,
37 | occupation: 'Developer'
38 | // key:'value'
39 | };
40 |
41 | for (let key in person) { //(let a in person) -> console.log(a);
42 | console.log(key); // prints "name", "age", "occupation"
43 | console.log(person[key]); // prints the corresponding values "John", 30, "Developer"
44 | }
45 |
46 |
47 | // For Of Loop
48 | // Loop Through The Value Of An Object
49 | // Object Must Be Iterable
50 |
51 | // Example
52 | const fruits = ['apple', 'banana', 'orange'];
53 |
54 | for (let fruit of fruits) {
55 | console.log(fruit); // prints "apple", "banana", "orange"
56 | }
57 |
58 | const message = 'Hello';
59 |
60 | for (let char of message) {
61 | console.log(char); // prints "H", "e", "l", "l", "o"
62 | }
63 |
64 |
65 | // While Loop
66 | // If Condition Never False -> Loop Will Never End -> Crush JS Run Time
67 | // Also Called In Infinite Loop -> Don't Try This Circus
68 |
69 | // Syntax
70 | // while(condition){
71 | // // Code To Be Executed
72 | // }
73 |
74 | // Example
75 | let i = 0;
76 | while (i < 5) {
77 | console.log(i); // prints numbers from 0 to 4
78 | i++;
79 | }
80 |
81 |
82 | // ALT + SHIFT + DOWN ARROW KEY -> Replicate Selected Code
83 |
84 |
85 | // Do.....While Loop
86 | // Do...While Loop -> While Loop Variant Which Run a At Least Once
87 | // Syntax
88 |
89 | // do {
90 | // // Code To Be Executed
91 | // } while(Condition)
92 |
93 | // Example
94 | let i = 0;
95 | do {
96 | console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once
97 | i++;
98 | } while (i < 5);
99 |
100 | let i = 6;
101 | do {
102 | console.log(i); // prints numbers from 0 to 4 -> Executed At Least Once
103 | i++;
104 | } while (i < 5);
105 |
106 | // Output -> 6
107 |
108 |
109 | // Functions
110 | // Functions are reusable blocks of code that perform a specific task. They help in organizing code, improving reusability, and reducing redundancy. A function can accept parameters (inputs) and return a value.
111 |
112 | // function myfun(parameter1, parameter2){
113 | // //Code -> Parameter Behave As Local Variables
114 | // }
115 |
116 | // myfun(6,7); -> Function Invocation
117 | // A. Function declaration:
118 | // B function declaration defines a named function that can be called later in the code.
119 |
120 | // Example
121 | function greet(name) {
122 | console.log(`Hello, ${name}!`);
123 | }
124 |
125 | greet("John"); // prints "Hello, John!"
126 | greet("Sarah"); // prints "Hello, Sarah!"
127 |
128 | // Function expression:
129 | // A function expression assigns a function to a variable. It can be anonymous or named.
130 |
131 | const greet = function (name) {
132 | console.log(`Hello, ${name}!`);
133 | };
134 |
135 | greet("John"); // prints "Hello, John!"
136 | greet("Sarah"); // prints "Hello, Sarah!"
137 |
138 | // Arrow function:
139 | // Arrow functions provide a concise syntax for writing functions. They are anonymous and lexically bind the this value.
140 |
141 | const greet = (name) => {
142 | console.log(`Hello, ${name}!`);
143 | };
144 |
145 | greet("John"); // prints "Hello, John!"
146 | greet("Sarah"); // prints "Hello, Sarah!"
147 |
148 | // Returning a value:
149 | // Functions can return a value using the return statement. The returned value can be stored in a variable or used directly.
150 |
151 | function add(a, b) {
152 | return a + b;
153 | }
154 |
155 | const result = add(3, 4);
156 | console.log(result); // prints 7
157 |
158 | // Default parameters:
159 | // Default parameters allow you to assign default values to function parameters if no argument is passed.
160 |
161 |
162 | function multiply(a, b = 1) {
163 | return a * b;
164 | }
165 |
166 | console.log(multiply(5)); // prints 5
167 | console.log(multiply(5, 2)); // prints 10
168 |
--------------------------------------------------------------------------------
/Ch 4 String Practice Set.js:
--------------------------------------------------------------------------------
1 | // Ch 4 String Practice Set
2 |
3 | // Q1)Write a program that counts the number of characters in a given string.
4 |
5 |
6 |
7 | // const str = "Hello, World!";
8 | // const count = str.length;
9 | // console.log(count); // Output: 13
10 |
11 |
12 | // Q2)Write a program that checks if a string contains a specific substring.
13 |
14 |
15 |
16 | // const str = "Hello, World!";
17 | // const substring = "World";
18 | // const containsSubstring = str.includes(substring);
19 | // console.log(containsSubstring); // Output: true
20 |
21 |
22 |
23 | // Q3)Write a program that converts a string to uppercase.
24 |
25 |
26 |
27 | // const str = "Hello, World!";
28 | // const uppercaseStr = str.toUpperCase();
29 | // console.log(uppercaseStr); // Output: HELLO, WORLD!
30 |
31 |
32 |
33 | // Q4)Write a program that extracts a portion of a string based on start and end indexes.
34 |
35 |
36 |
37 | // const str = "Hello, World!";
38 | // const extractedStr = str.slice(7, 12);
39 | // console.log(extractedStr); // Output: World
40 |
41 |
42 | // Q5)Write a program that replaces a specific substring with another substring.
43 |
44 |
45 |
46 | // const str = "Hello, John!";
47 | // const newStr = str.replace("John", "Alice");
48 | // console.log(newStr); // Output: Hello, Alice!
49 |
50 |
51 |
52 | // Q6)Write a program that splits a string into an array of substrings based on a delimiter.
53 |
54 |
55 |
56 | // const str = "Hello, World!";
57 | // const arr = str.split(",");
58 | // console.log(arr); // Output: ["Hello", " World!"]
59 |
60 | // Q7)Write a program that checks if a string starts with a specific character or substring.
61 |
62 |
63 |
64 | // const str = "Hello, World!";
65 | // const startsWithHello = str.startsWith("Hello");
66 | // console.log(startsWithHello); // Output: true
67 |
68 |
69 | // Q8)Write a program that checks if a string ends with a specific character or substring.
70 |
71 |
72 |
73 | // const str = "Hello, World!";
74 | // const endsWithWorld = str.endsWith("World!");
75 | // console.log(endsWithWorld); // Output: true
76 |
77 |
78 | // Q9)Write a program that trims whitespace from the beginning and end of a string.
79 |
80 |
81 |
82 | // const str = " Hello, World! ";
83 | // const trimmedStr = str.trim();
84 | // console.log(trimmedStr); // Output: Hello, World!
85 |
86 |
87 | // Q10)Write a program that checks if a string is empty.
88 |
89 |
90 |
91 | // const str = "";
92 | // const isEmpty = str.length === 0;
93 | // console.log(isEmpty); // Output: true
--------------------------------------------------------------------------------
/Ch 4 String.js:
--------------------------------------------------------------------------------
1 | // Strings
2 |
3 | // 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.
4 |
5 | // Strings are used to store and manipulate text
6 |
7 | // String -> Collection of characters
8 |
9 | // Single Quotes -> let name = 'dp';
10 | // Double Quotes -> let name = "dp";
11 |
12 | let name = "dp";
13 | // console.log(name[3]); -> undefined
14 |
15 | // Template Literals
16 |
17 | // After ES6, Template Literals came into use, utilizing backticks (`).
18 |
19 | let boy1 = "hmm";
20 | let boy2 = 'ok';
21 |
22 | // Print "hmm nice ok"
23 | // let sentence = `boy1 "nice" 'is' boy2` -> We make a string using single or double quotes, both usage possible if string is made through backticks
24 |
25 | // String Interpolation
26 | let sentence = `${boy1} nice ${boy2}`;
27 | console.log(sentence); // Output: hmm nice ok
28 |
29 | let fruit = `Bana\'na`; // Bana'na
30 | console.log(fruit);
31 |
32 | // \' -> Escape character -> Count as one character
33 | // \n -> New line
34 | // \t -> Tab
35 | // \r -> Carriage return
36 |
37 | // String Methods & Properties
38 |
39 | // Accessing Characters:
40 | // Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0.
41 |
42 | const message = 'Hello';
43 | console.log(message[0]); // Output: H
44 | console.log(message[3]); // Output: l
45 |
46 | // String Concatenation:
47 | // Strings can be concatenated using the + operator or the concat() method.
48 |
49 | const firstName = 'John';
50 | const lastName = 'Doe';
51 | const fullName = firstName + ' ' + lastName;
52 | console.log(fullName); // Output: John Doe
53 |
54 | // Using concat()
55 | const greetingMessage = 'Hello, ';
56 | const nameConcat = 'John';
57 | const greeting = greetingMessage.concat(nameConcat);
58 | console.log(greeting); // Output: Hello, John
59 |
60 | // Finding Substrings:
61 | // 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.
62 |
63 | const welcomeMessage = 'Hello, world!';
64 | console.log(welcomeMessage.indexOf('world')); // Output: 7
65 | console.log(welcomeMessage.indexOf('open')); // Output: -1
66 |
67 | // Extracting Substrings:
68 | // The slice() method extracts a portion of a string based on the start and end indexes.
69 |
70 | console.log(welcomeMessage.slice(0, 5)); // Output: Hello
71 | console.log(welcomeMessage.slice(7)); // Output: world!
72 |
73 | // Replacing Substrings:
74 | // The replace() method replaces a specified substring with another substring.
75 |
76 | const personalizedMessage = 'Hello, John!';
77 | console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice!
78 |
79 | // Splitting Strings:
80 | // The split() method splits a string into an array of substrings based on a specified delimiter.
81 |
82 | console.log(welcomeMessage.split(' ')); // Output: ["Hello,", "world!"]
83 |
84 | // Checking if a String Contains a Substring:
85 | // The includes() method checks if a string contains a specified substring and returns true or false.
86 |
87 | console.log(welcomeMessage.includes('World')); // Output: true
88 | console.log(welcomeMessage.includes('open')); // Output: false
89 |
90 | // String Length:
91 | // The length property returns the number of characters in a string.
92 |
93 | console.log(welcomeMessage.length); // Output: 13
94 |
95 | // String Slice:
96 | // The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string.
97 |
98 | console.log(welcomeMessage.slice(7)); // Output: world!
99 | console.log(welcomeMessage.slice(0, 5)); // Output: Hello
100 |
101 | // String Substring:
102 | // The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string.
103 |
104 | console.log(welcomeMessage.substring(7)); // Output: world!
105 | console.log(welcomeMessage.substring(0, 5)); // Output: Hello
106 |
107 | // String Substr:
108 | // The substr() method extracts a portion of a string based on the start index and length. It returns a new string.
109 |
110 | console.log(welcomeMessage.substr(7)); // Output: world!
111 | console.log(welcomeMessage.substr(0, 5)); // Output: Hello
112 |
113 | // String Replace:
114 | // The replace() method replaces a specified substring with another substring. It returns a new string.
115 |
116 | console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice!
117 |
118 | // String ReplaceAll:
119 | // The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021)
120 |
121 | const repetitiveMessage = 'Hello, John! John is a good guy.';
122 | console.log(repetitiveMessage.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy.
123 |
124 | // String toUpperCase and toLowerCase:
125 | // The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string.
126 |
127 | console.log(welcomeMessage.toUpperCase()); // Output: HELLO, WORLD!
128 | console.log(welcomeMessage.toLowerCase()); // Output: hello, world!
129 |
130 | // String Concatenation:
131 | // The concat() method concatenates two or more strings and returns a new string.
132 |
133 | console.log(firstName.concat(' ', lastName)); // Output: John Doe
134 |
135 | // String Trim:
136 | // The trim() method removes whitespace from both ends of a string and returns a new string.
137 |
138 | const messageWithWhitespace = ' Hello, world! ';
139 | console.log(messageWithWhitespace.trim()); // Output: Hello, world!
140 |
141 | // String TrimStart and TrimEnd:
142 | // 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)
143 |
144 | console.log(messageWithWhitespace.trimStart()); // Output: Hello, world!
145 | console.log(messageWithWhitespace.trimEnd()); // Output: Hello, world!
146 |
147 | // String PadStart and PadEnd:
148 | // 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)
149 |
150 | const paddedMessage = 'Hello';
151 | console.log(paddedMessage.padStart(10, '*')); // Output: *****Hello
152 | console.log(paddedMessage.padEnd(10, '-')); // Output: Hello-----
153 |
154 | // String CharAt and CharCodeAt:
155 | // The charAt() method returns the character at a specified index in a string.
156 | // The charCodeAt() method returns the Unicode value of the character at a specified index in a string.
157 |
158 | console.log(message.charAt(0)); // Output: H
159 | console.log(message.charCodeAt(0)); // Output: 72
160 |
161 | // String Split:
162 | // The split() method splits a string into an array of substrings based on a specified delimiter.
163 |
164 | console.log(welcomeMessage.split(',')); // Output: ["Hello", " World!"]
165 |
166 | // Method summary:
167 | // String length
168 | // String slice()
169 | // String substring()
170 | // String substr()
171 | // String replace()
172 | // String replaceAll()
173 | // String toUpperCase()
174 | // String toLowerCase()
175 | // String concat()
176 | // String trim()
177 | // String trimStart()
178 | // String trimEnd()
179 | // String padStart()
180 | // String padEnd()
181 | // String charAt()
182 | // String charCodeAt()
183 | // String split()
--------------------------------------------------------------------------------
/Ch 5 Array Practice Set.js:
--------------------------------------------------------------------------------
1 | // Ch 5 Array Practice Set
2 |
3 |
4 |
5 | // Q1)How do you create an empty array in JavaScript?
6 |
7 | // Answer:
8 |
9 | // const emptyArray = [];
10 |
11 |
12 | // Q2)How do you check if an array is empty in JavaScript?
13 |
14 | // Answer:
15 |
16 | // const array = [];
17 |
18 | // if (array.length === 0) {
19 | // console.log("The array is empty");
20 | // } else {
21 | // console.log("The array is not empty");
22 | // }
23 |
24 |
25 | // Q3)How do you add elements to the end of an array in JavaScript?
26 |
27 | // Answer:
28 |
29 | // const array = [1, 2, 3];
30 | // array.push(4, 5);
31 | // console.log(array); // Output: [1, 2, 3, 4, 5]
32 |
33 |
34 | // Q4)How do you access an element at a specific index in an array?
35 |
36 | // Answer:
37 |
38 | // const array = [1, 2, 3];
39 | // const element = array[1];
40 | // console.log(element); // Output: 2
41 |
42 |
43 | // Q5)How do you remove the last element from an array in JavaScript?
44 |
45 | // Answer:
46 |
47 | // const array = [1, 2, 3];
48 | // const removedElement = array.pop();
49 | // console.log(array); // Output: [1, 2]
50 | // console.log(removedElement); // Output: 3
51 |
52 |
53 | // Q6)How do you find the index of a specific element in an array?
54 |
55 | // Answer:
56 |
57 | // const array = [1, 2, 3, 4, 5];
58 | // const index = array.indexOf(3);
59 | // console.log(index); // Output: 2
60 |
61 |
62 | // Q7)How do you concatenate two arrays in JavaScript?
63 |
64 | // Answer:
65 |
66 | // const array1 = [1, 2, 3];
67 | // const array2 = [4, 5, 6];
68 | // const concatenatedArray = array1.concat(array2);
69 | // console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]
70 |
71 |
72 | // Q8)How do you check if an element exists in an array?
73 |
74 | // Answer:
75 |
76 | // const array = [1, 2, 3, 4, 5];
77 | // const elementExists = array.includes(3);
78 | // console.log(elementExists); // Output: true
79 |
80 |
81 | // Q9)How do you find the maximum value in an array?
82 |
83 | // Answer:
84 |
85 | // const array = [4, 2, 7, 5, 1];
86 | // const max = Math.max(...array);
87 | // console.log(max); // Output: 7
88 |
89 |
90 | // Q10)How do you reverse the order of elements in an array?
91 |
92 | // Answer:
93 |
94 | // const array = [1, 2, 3, 4, 5];
95 | // array.reverse();
96 | // console.log(array); // Output: [5, 4, 3, 2, 1]
--------------------------------------------------------------------------------
/Ch 6 JS In Browser.js:
--------------------------------------------------------------------------------
1 | // Element Tab -> All Element
2 | // console Tab -> All The Error Plus Logs
3 | // Network Tab -> All The Network Request And Requirement
4 |
5 | // External File For Js -> File Cache Ho Jati he So Website Fast Work Karti He
6 | // We Can Add Js In Script Tag Also
7 | //
8 | //
9 |
10 | // Separation Of Concern and Cashing
11 |
12 | // Js Console Object
13 | // console.log(console)
14 | // console.error(error)
15 | // console.assert(assert)
16 | // console.clear()
17 | // console.table(table)
18 | // console.warn(warn)
19 | // console.info(info)
20 | // console.time(time)
21 | // console.timeEnd(timeEnd)
22 |
23 | // List All Method
24 | // console.log(console)
25 |
26 | // Output And Return Type Is There
27 | // console.log("Hey Darshan")
28 | // Output :
29 | // Hey Darshan
30 | // Undefined
31 |
32 | // Alert Prompt And Confirm
33 | // Alert -> Alert Box Show Karta Hai
34 | // Prompt -> Prompt Box Show Karta Hai -> Input Lene Ke Liye
35 | // Confirm -> Confirm Box Show Karta Hai -> Yes Or No Lene Ke Liye
36 |
37 | // alert("Enter The Value Of A")
38 | // let a = prompt("Enter A Here: ")
39 | // let a = prompt("Enter A Here: ", "578") // Default Value
40 | // document.write(a)
41 |
42 |
43 | // Confirm -> Yes Or No Lene Ke Liye
44 | // let write = confirm("Do You Want To Write It To The Page")
45 | // if (write) {
46 | // document.write(a)
47 | // } else {
48 | // document.write("Please Allow Me To Write")
49 | // }
50 |
51 | // This Will Stop Screen Execution Thats Why Not Suggested To Use That In User Side Plus Look Like Old Vintage Website So -> Use In Admin Panel
52 |
53 | // BOM And DOM
54 |
55 | // BOM -> Browser Object Model
56 | // DOM -> Document Object Model
57 | console.log(window)
58 | // window.console.log(window) -> Same Work Above
59 |
60 | // window is global object under that -> Bom , Dom , Js Core Feature Lies
61 |
62 | // Apke Pure HTML Page ko Document Represent Karta Hai -> Pure Page Ka Object Banke Usko Document Name De Diya Gaya He
63 | console.log(document)
64 | document.body.style.background = "yellow"
65 |
66 |
67 |
68 | // BOM (Browser Object Model):
69 | // 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.
70 |
71 |
72 | // Location href = "https://dpvasani56.com" -> Redirect To Another URL
73 |
74 | // console.log(window) => All Method
75 | // Window Object -> Global Object
76 |
--------------------------------------------------------------------------------
/Ch 6 JavaScript In Browser Practice Set.js:
--------------------------------------------------------------------------------
1 | // Ch 6 JavaScript In Browser Practice Set
2 |
3 | // Q1)How can you log a message to the console using the console object?
4 |
5 | // console.log("Hello, World!");
6 |
7 |
8 | // Q2)How can you display an error message in the console using the console object?
9 |
10 | // console.error("An error occurred.");
11 |
12 |
13 | // Q3)How can you clear the console using the console object?
14 |
15 | // console.clear();
16 |
17 |
18 | // Q4)How can you log a warning message to the console using the console object?
19 |
20 | // console.warn("This is a warning.");
21 |
22 |
23 | // Q5)How can you display tabular data as a table in the console using the console object?
24 |
25 | // const data = [
26 | // { name: "John", age: 25 },
27 | // { name: "Jane", age: 30 },
28 | // { name: "Bob", age: 35 }
29 | // ];
30 | // console.table(data);
31 |
32 | // Q6)How can you write an error message to the console if a condition is false using the console object?
33 |
34 | // const value = 10;
35 | // console.assert(value > 20, "Value should be greater than 20.");
36 |
37 |
38 | // Q7)How can you measure the time taken to execute a block of code using the console object?
39 |
40 | // console.time("Timer");
41 | // // Code block to measure execution time
42 | // console.timeEnd("Timer");
43 |
44 |
45 | // Q8)How can you prompt the user to enter their name and log it to the console using the prompt function?
46 |
47 | // const name = prompt("Enter your name:");
48 | // console.log("Hello, " + name + "!");
49 |
50 |
51 | // Q9)How can you display an alert box with a message to the user using the alert function?
52 |
53 | // alert("This is an alert message.");
54 |
55 |
56 | // Q10)How can you display a confirm dialog box and log the user's choice to the console using the confirm function?
57 |
58 | // const result = confirm("Are you sure you want to delete this item?");
59 | // if (result === true) {
60 | // console.log("Item deleted.");
61 | // } else {
62 | // console.log("Deletion cancelled.");
63 | // }
--------------------------------------------------------------------------------
/Ch 6 JavaScript In Browser.js:
--------------------------------------------------------------------------------
1 | // JavaScript In Browser
2 | // Semicolon Are Optional
3 | // JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
4 | // JS -> Initially Created To Make Web Pages
5 | // Browser Has Embedded Engine -> JavaScript Engine or JavaScript Run Time
6 | // JS Ability In Browser Is Very Limited
7 |
8 |
9 | // Developer Tool -> Every Browser Has This -> Make Developer Life Easier
10 |
11 |
12 | // Element - Console - Network
13 | // All HTML Element - All Error + Log - All Network Request
14 |
15 |
16 | // Use JS In Browser
17 |
18 | // Scripts can be placed in the , or in the section of an HTML page, or in both.
19 | // To use JavaScript in a web page, you can embed it directly within the HTML document.
20 |
21 | // Inline Script: JavaScript code can be placed directly within the
27 |
28 |
29 | // External Script: JavaScript code can also be stored in an external file and linked to the HTML document using the This Must Be In Body Tag
32 |
33 |
34 | // Example Of JS In Browser
35 |
36 | //
37 | //
38 | //
39 | // JavaScript in the Browser
40 | //
41 | //
42 | // Hello, World!
43 | // Change Text
44 |
45 | //
58 | //
59 | //
60 |
61 |
62 | // Console Object Method
63 |
64 |
65 | // The console object in JavaScript provides a set of methods that allow developers to interact with the browser's console. These methods are useful for logging messages, debugging code, and monitoring the execution of JavaScript code. Here are some commonly used methods of the console object along with examples:
66 |
67 | // console.log(console) -> List All Console Method
68 |
69 | // External JS is Better To Use -> Separation Of Concerns & Browser Caching -> Browser Save That FIle SO We Not Load Again It
70 |
71 | // log(): Logs a message to the console.
72 |
73 | // console.log('Hello, World!'); // Output: Hello, World!
74 |
75 |
76 | // error(): Logs an error message to the console.
77 |
78 | // console.error('An error occurred.'); // Output: An error occurred.
79 |
80 |
81 | // warn(): Logs a warning message to the console.
82 |
83 | // console.warn('This is a warning.'); // Output: This is a warning.
84 |
85 |
86 | // info(): Logs an informational message to the console.
87 |
88 | // // Output: This is an information.
89 |
90 |
91 | // debug(): Logs a debug message to the console.
92 |
93 | // console.debug('Debugging information.'); // Output: Debugging information.
94 |
95 |
96 | // assert(): Writes an error message to the console if the provided condition is false.
97 |
98 | // const value = 10;
99 | // console.assert(value > 20, 'Value should be greater than 20.'); // Output: Value should be greater than 20.
100 |
101 |
102 | // clear(): Clears the console.
103 |
104 | // console.clear(); // Clears the console
105 |
106 |
107 | // table(): Displays tabular data as a table in the console.
108 |
109 | // const data = [
110 | // { name: 'John', age: 25 },
111 | // { name: 'Jane', age: 30 },
112 | // { name: 'Bob', age: 35 }
113 | // ];
114 | // console.table(data);
115 | // Output:
116 | // ┌─────┬──────┬─────┐
117 | // │ (index) │ name │ age │
118 | // ├─────┼──────┼─────┤
119 | // │ 0 │ 'John' │ 25 │
120 | // │ 1 │ 'Jane' │ 30 │
121 | // │ 2 │ 'Bob' │ 35 │
122 | // └─────┴──────┴─────┘
123 | // count(): Logs the number of times count() has been called with the provided label.
124 |
125 | // console.count('Counter'); // Output: Counter: 1
126 | // console.count('Counter'); // Output: Counter: 2
127 | // console.count('Another Counter'); // Output: Another Counter: 1
128 | // console.count('Counter'); // Output: Counter: 3
129 |
130 |
131 | // time() and timeEnd(): Measures the time taken to execute a block of code.
132 |
133 | // console.time('Timer');
134 | // // Code block to measure execution time
135 | // console.timeEnd('Timer'); // Output: Timer:
136 | // While Loop Vs For Loop
137 |
138 | console.time("forLoop")
139 | for (let i = 0; i < 500; i++) {
140 | console.log(233)
141 | }
142 |
143 | console.timeEnd("forLoop")
144 |
145 | console.time("whileLoop")
146 |
147 | let i = 0;
148 | while (i < 500) {
149 | console.log(233)
150 | i++;
151 | }
152 |
153 | console.timeEnd("whileLoop")
154 |
155 | // List
156 |
157 | // assert() -> Writes an error message to the console if a assertion is false
158 | // clear() -> Clears the console
159 | // count() -> Logs the number of times that this particular call to count() has been called
160 | // error() -> Outputs an error message to the console
161 | // group() -> Creates a new inline group in the console. This indents following console messages by an additional level, until console.groupEnd() is called
162 | // groupCollapsed() -> Creates a new inline group in the console. However, the new group is created collapsed. The user will need to use the disclosure button to expand it
163 | // groupEnd() -> Exits the current inline group in the console
164 | // info() -> Outputs an informational message to the console
165 | // log() -> Outputs a message to the console
166 | // table() -> Displays tabular data as a table
167 | // time() -> Starts a timer (can track how long an operation takes)
168 | // timeEnd() -> Stops a timer that was previously started by console.time()
169 | // trace() -> Outputs a stack trace to the console
170 | // warn() -> Outputs a warning message to the console
171 |
172 |
173 | // Interaction In JavaScript: Prompt, Alert, And Confirm
174 | // BOM Functions
175 | // 1. prompt -> Take Input From User
176 |
177 | // Example:
178 |
179 | // const name = prompt('Enter your name:');
180 | // console.log('Hello, ' + name + '!');
181 |
182 | // inp = prompt("Hi", "No") -> No Is Optional Default Value
183 |
184 | // This example prompts the user to enter their name and stores the entered value in the name variable. It then logs a greeting message to the console using the entered name.
185 |
186 |
187 | // 2. alert
188 |
189 | // The alert method displays a dialog box with a message to the user. It is primarily used to show information or provide notifications to the user.
190 |
191 | // Example:
192 |
193 | // alert('This is an alert message.');
194 | // This example displays an alert box with the message "This is an alert message."
195 |
196 |
197 | // 3. confirm
198 |
199 | // The confirm method displays a dialog box with a message and two buttons: OK and Cancel.It allows the user to confirm or cancel an action.It returns a boolean value indicating the user's choice (true for OK and false for Cancel).
200 |
201 | // Example:
202 |
203 | // const result = confirm('Are you sure you want to delete this item?');
204 | // if (result === true) {
205 | // console.log('Item deleted.');
206 | // } else {
207 | // console.log('Deletion cancelled.');
208 | // }
209 | // This example shows a confirm dialog asking the user if they want to delete an item. Depending on the user's choice, it logs either "Item deleted." or "Deletion cancelled." to the console.
210 |
211 |
212 | // Window Object, Dom & Bom
213 |
214 |
215 | // +---------------------------+
216 | // | |
217 | // | Window |
218 | // | |
219 | // +---------------------------+
220 | // |
221 | // | Provides access to:
222 | // |
223 | // +---------------------------+
224 | // | |
225 | // | Document Object Model |
226 | // | (DOM) |
227 | // | |
228 | // +---------------------------+
229 | // |
230 | // | Provides access to:
231 | // |
232 | // +---------------------------+
233 | // | |
234 | // | Browser Object Model |
235 | // | (BOM) |
236 | // | |
237 | // +---------------------------+
238 | // |
239 | // | Provides access to:
240 | // |
241 | // +---------------------------+
242 | // | |
243 | // | JavaScript Core |
244 | // | |
245 | // +---------------------------+
246 |
247 | // DOM (Document Object Model):
248 | // The Document Object Model represents the structure of an HTML or XML document as a tree-like structure, where each element in the document is represented as a node. The DOM provides a way to interact with the content and structure of a web page using programming languages like JavaScript. The window object in JavaScript provides access to the DOM, allowing you to manipulate elements, change their attributes, and handle events. You can use methods like getElementById(), querySelector(), and properties like innerHTML to interact with the DOM through the window object.
249 |
250 |
251 | // Simply Dom Represent The Page Content As HTML
252 |
253 | // document.body -> Page Body As JS Object
254 | // document.body.style.background="Green"
255 | // Change Page Background To Green
256 |
257 |
258 | // BOM (Browser Object Model):
259 | // 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.
260 |
261 |
262 | // Location href = "https://dpvasani56.com" -> Redirect To Another URL
263 |
264 | // console.log(window) => All Method
265 | // Window Object -> Global Object
--------------------------------------------------------------------------------
/Ch 7 DOM Practice Set.js:
--------------------------------------------------------------------------------
1 | // Ch 7 DOM Practice Set
2 |
3 | // Q1: How can you access an HTML element by its unique ID?
4 | // A: By using the getElementById method. For example:
5 |
6 | const element = document.getElementById('myElement');
7 |
8 |
9 | // Q2: How can you access HTML elements based on their class name?
10 | // A: By using the getElementsByClassName method. For example:
11 |
12 | const elements = document.getElementsByClassName('myClass');
13 |
14 |
15 | // Q3: How can you access HTML elements based on their tag name?
16 | // A: By using the getElementsByTagName method. For example:
17 |
18 | const elements = document.getElementsByTagName('h1');
19 |
20 |
21 | // Q4: How can you access HTML elements using CSS selectors?
22 | // A: By using the querySelector method. For example:
23 |
24 | const element = document.querySelector('.mySelector');
25 |
26 |
27 | // Q5: How can you modify the content of an HTML element?
28 | // A: By using the innerHTML property. For example:
29 |
30 | const myDiv = document.getElementById('myDiv');
31 | myDiv.innerHTML = 'Hello, JavaScript!';
32 |
33 |
34 | // Q6: How can you modify the attributes of an HTML element?
35 | // A: By using the setAttribute method. For example:
36 |
37 | const myImage = document.getElementById('myImage');
38 | myImage.setAttribute('src', 'new_image.jpg');
39 |
40 |
41 | // Q7: How can you modify the styles of an HTML element?
42 | // A: By using the style property. For example:
43 |
44 | const myDiv = document.getElementById('myDiv');
45 | myDiv.style.backgroundColor = 'red';
46 |
47 |
48 | // Q8: How can you add a class to an HTML element?
49 | // A: By using the classList.add method. For example:
50 |
51 | const myDiv = document.getElementById('myDiv');
52 | myDiv.classList.add('highlight');
53 |
54 |
55 | // Q9: How can you create a new HTML element and append it to the document?
56 | // A: By using the createElement and appendChild methods. For example:
57 |
58 | const newParagraph = document.createElement('p');
59 | newParagraph.innerHTML = 'This is a new paragraph.';
60 | document.body.appendChild(newParagraph);
61 |
62 |
63 | // Q10: How can you check if an element contains another element as a descendant?
64 | // A: By using the contains method. For example:
65 |
66 | const parentElement = document.getElementById('parent');
67 | const childElement = document.getElementById('child');
68 | const isChildOfParent = parentElement.contains(childElement);
--------------------------------------------------------------------------------
/Ch 7 Js DOM.js:
--------------------------------------------------------------------------------
1 | // HTML Ko Convert Kar Diya He Js Object Me -> All Node Are Object
2 | // Text Node
3 | // Element Node
4 | // Comment Node
5 |
6 | // Auto Correction In HTML -> If Any Error In HTML Then It Will Be Auto Corrected
7 |
8 | // Walking The DOM
9 |
10 | // DOM Tree Traversal
11 | // document.body -> Page Body Tag
12 | // document.documentElement -> HTML Tag -> Page
13 | // document.head -> Head Tag
14 | // document.title -> String
15 |
16 | // document.body can be Null If The JavaScript Is Written Before The Body Tag
17 | // Children Of An Element -> Direct As Well As Deeply Nested Elements Of An Element Are Called Its Children
18 |
19 | // Child Nodes: Elements That Are Direct Children For Example Head And Body Are Children Of
20 |
21 | // Descendant Nodes: All Necessary Nodes Are Called Descendant Nodes For Example Head, Body, Title, Meta, Etc. Are Descendant Nodes Of
22 |
23 | // All Nested Elements , CHildren , Their Children And So On Are Called Their Siblings
24 |
25 | // First Child -> First Element Child -> element.firstChild
26 | // Last Child -> Last Element Child -> element.lastChild
27 | // Child Nodes (Element.childNodes) -> All Children
28 |
29 | // Following Are Always True
30 | // element.firstChild === element.childNodes[0]
31 | // element.lastChild === element.childNodes[element.childNodes.length - 1]
32 |
33 | // There Is Also A Method Element.hasChildNodes() To Check Whether There Are Any Child Nodes (Element.childNodes) Or Not
34 |
35 | // Child Nodes Are Not An Array But Can Be Converted Into Array -> Array.from(collection)
36 |
37 | // 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
38 |
39 | // Notes On Dom Collection
40 | // They Are Read Only
41 | // They Are Live Element.childNodes Variable (Reference) Will Be Updated Automatically If Child Nodes Of The Element Is Changed
42 | // They Are Iterable Using For...Of Loop
43 |
44 | // Siblings And Their Parents
45 |
46 | // Siblings Are Nodes That Are Children Of The Same Parent
47 | // For Example And Are Siblings. Siblings Have Same Parent In This Case
48 | // Is Said To Be The "Next" Or "Right" Sibling Of , Is Said To Be The "Previous" Or "Left" Sibling Of
49 | // The Next Sibling Is In NextSibling Property , And The Previous One Is In previousSibling Property
50 | // The Parent Is In parentNode Property
51 | // alert(document.documentElement.parentNode) -> Document
52 | // alert(document.documentElement.parentElement) -> Null
53 | // parentElement -> Ak Element Hai To Hi Return Hoga Verna Null Return Hoga
54 |
55 | // console.log(document.body.firstChild)
56 | // a = document.body.firstChild
57 | // console.log(a.parentNode)
58 | // console.log(a.parentElement)
59 | // console.log(a.firstChild.nextSibling)
60 |
61 |
62 |
63 | // Element Only Navigation
64 |
65 | // 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
66 |
67 |
68 | // let b = document.body
69 | // 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
70 | // console.log("First Element Child Of b Is : ", b.firstElementChild)
71 | // Only Element Type Ka First Child Dekhne Ko Milta He
72 |
73 | // const changeBgRed =()=>{
74 | // document.body.firstElementChild.style.background = "red"
75 |
76 | // }
77 |
78 | // document.previousElementSibling -> Previous Sibling Which Is An Element
79 | // document.nextElementSibling -> Next Sibling Which Is An Element
80 | // document.firstElementChild -> First Element Child
81 | // document.lastElementChild -> Last Element Child
82 |
83 | // Table Links
84 | // Certain DOM Elements May Provide Additional Properties Specific To Their Type For Example Table Elements Support -> table.rows -> Collection Of Tr Elements
85 |
86 | // table.rows -> Collection Of Tr Elements
87 | // table.caption -> Reference To
88 | // table.tHead -> Reference To
89 | // table.tFoot -> Reference To
90 | // table.tBodies -> Collection Of Elements
91 | // tbody.rows -> Collection Of Inside
92 | // tr.cells -> Collection Of Td And Th
93 | // tr.sectionRowIndex -> Index Of Tr In It's Section
94 | // tr.rowIndex -> Row Number Starting From 0
95 | // td.cellIndex -> No Of Cells In Row
96 |
97 |
98 | // Searching The DOM
99 | // document.getElementById() -> To Search Element By Id
100 | // document.querySelectorAll(.card-title) -> To Search Multiple Elements With Same CSS Selector
101 | // document.querySelector() -> To Search Single Element With CSS Selector
102 | // document.getElementsByTagName() -> To Search Element By Tag Name
103 | // document.getElementsByClassName() -> To Search Element By Class Name
104 | // document.getElementsByName() -> To Search Element By Name Attribute
105 |
106 | // let ctitle = document.getElementsByClassName("card-title")[0]
107 | // console.log(document.quarySelector(".card-title").getElemetByClassName("card-title"))
108 |
109 | // No S -> Return One Element
110 | // S -> Return All Elements -> Elements
111 |
112 | // Matches, Closest & Contains Methods
113 | // elem.matches(CSS) -> To Check If Element Matches The Given CSS Selector
114 | // elem.closest(CSS) -> To Look For The Nearest ancestor That Matches The Given CSS Selector.
115 | // No Than Go to Perent Hai TO Return So And So
116 |
117 | // let id1 = document.getElementById("id1")
118 | // let sp1 = document.getElementById("sp1")
119 | // console.log(id1.matches(".class"))
120 |
121 | // elem.contains(elem) -> Returns True If Element B Is Inside Element A (A Descendant Of B) Or When Element A == Element B
122 |
123 |
124 | // Chapter 7 Practice Set
125 | // Q1 -> Create A Navbar And Change The Color Of Its First Element To Red
126 | // document.getElementsByTagName("nav")[0].firstElementChild.style.color = "red"
127 | // Q2 -> Create A Table Using JavaScript Which Background Color To Green
128 | // document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
129 | // Q3 -> Create An Element With 3 Children. Now Change The Color Of First And Last Element To Green
130 | // document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
131 | // document.getElementsByTagName("nav")[0].lastElementChild.style.color = "green"
132 | // Q4 -> Write A JavaScript Code To Change Background Of All Tags To Cyan
133 | // Array.from(document.getElementsByTagName("li")).forEach((element) => {
134 | // element.style.background = "cyan";
135 | // })
136 | // Q5 -> Which Of The Following Is Used To Look For The Farthest Ancestor That Matches A Given CSS Selector
137 | // (a) matches (b) closest (c) contains (d) none of these
138 | // Ans -> None Of These
139 |
--------------------------------------------------------------------------------
/Ch 8 Event & Other DOM Properties.js:
--------------------------------------------------------------------------------
1 | // Event & Other DOM Properties
2 |
3 | // Event Handling
4 | // Now, let's discuss Event Handling using Javascript:
5 | // Event Handling:
6 | // Event handling in JavaScript with the HTML DOM
7 | // (Document Object Model) allows you to respond
8 | // to user interactions or other events that occur on
9 | // a webpage
10 |
11 |
12 | // Event Types:
13 | // Events can be triggered by various actions, such as a user
14 | // clicking a button, hovering over an element, submitting a
15 | // form, or even the page finishing loading. Some common
16 | // event types include click, mouseover, submit, keydown,
17 | // and load. You can attach event handlers to these events
18 | // to execute JavaScript code when the event occurs. like
19 | // this:
20 | Click me
21 |
22 | var button = document.getElementById("myButton");
23 | // Event handler for the click event
24 | button.addEventlistener("click", function() f
25 | alert("Button clicked!");
26 | });
27 |
28 | // This code finds a button on a web page, listens for a
29 | // click on that button, and when the click happens, it
30 | // shows a pop-up message saying 'Button clicked!" to
31 | // let the user know that the button was indeed
32 | // clicked.
33 |
34 |
35 | // Attaching Event Handlers:
36 | // To attach an event handler to an element, you can use
37 | // the addEventListener method. This method takes the
38 | // event type as the first argument and a callback
39 | // function as the second argument. The callback function
40 | // is executed when the event is triggered.Like this:
41 |
42 | var button = document.getElementById("myButton");
43 | // Event handler for the click event
44 | function handleClick() {
45 | }
46 | alert("Button clicked!");
47 | // Attach the event handler to the button
48 | button.addEventListener("click", handleClick);
49 |
50 | // This code finds a button on a web page, defines a function
51 | // that displays an alert when the button is clicked, and attaches
52 | // that function as an event handler to the button. When the
53 | // button is clicked, the function is triggered, and an alert box
54 | // pops up with the message "Button clicked!" to let the user
55 | // know that the button was clicked.
56 |
57 |
58 | // Removing Event Handlers:
59 | // If you no longer need an event handler, you can remove it
60 | // using the removeEventListener method. This method
61 | // requires the same event type and callback function that were
62 | // used to attach the event handler.
63 |
64 | var button = document.getElementById("myButton");
65 | // Event handler for the click event
66 | function handleclick() {
67 | alert("Button clicked!");
68 | }
69 | // Attach the event handler to the button
70 | button.addEventListener("click", handleClick);
71 | // Remove the event handler from the button
72 | button.removeEventlistener("click", handleClick);
73 |
74 | // This code attaches a click event handler to a button element with the
75 | // id "'myButton". When the button is clicked, an alert saying "Button
76 | // clicked!" will be shown.
77 | // Later, the event handler is removed from the button using the
78 | // removeEventListener method. This means that when the button is
79 | // clicked again, the handleClick function will no longer be executed.
80 |
81 | // Example:
82 |
83 | // Click me
84 |
85 | //
92 |
93 | {/* output
94 | 127.0.0.1:5501 says
95 | Button clicked!
96 | OK
97 | Click me */}
--------------------------------------------------------------------------------
/Ch 8 Events And Other DOM Properties.js:
--------------------------------------------------------------------------------
1 | // console.log(document.getElementsByTagName('span')[0])
2 | // console.dir(document.getElementsByTagName('span')[0]) // -> Span Ko Object Dikhayega With Its Properties
3 |
4 | // console.log -> Shows the element DOM tree
5 | // console.dir -> Shows the element as an object with its properties
6 |
7 | // console.log(document.body.firstChild.nodeName)
8 | // console.log(document.body.firstElementChild.nodeName)
9 |
10 | // TagName/ NodeName
11 | // TagName -> Only Exists For Element Nodes
12 | // NodeName -> Defined For Any Node (Text, Comment, etc)
13 |
14 | // innerHTML / outerHTML
15 | // innerHTML -> The Inner HTML Property allows to get the HTML inside the element as a string. -> Work For Element Nodes Only
16 |
17 | // outerHTML -> The outerHTML property contains the full HTML. -> Work For All Nodes
18 |
19 | // outerHTML Property Contain The Full HTML innerHTML + The Element Itself
20 | // first.innerHtml -> Help In Get Or Set The Inner HTML
21 | // first.innerHtml = "Hey I Am Italic " -> Insertion
22 |
23 | // first.outerHTML -> Help In Get Or Set The Outer HTML
24 | // Output -> Hey I Am Italic
25 |
26 |
27 | // document.body.firstChild.data -> Gives The Data Of The First Child
28 | // document.body.firstChild.nodeValue -> Same As Data
29 |
30 | // Text Content
31 | // The textContent property allows to get the text inside the element as a string. Only Works For Element Nodes
32 |
33 | // console.log(document.body.textContent)
34 |
35 | // Hidden Property
36 | // The hidden attribute and the DOM property specifies whether the element is visible or not.
37 | // first.hidden = false -> Shows The Element
38 | // first.hidden = true -> Hides The Element
39 |
40 | // Attributes Method
41 | // 1. elem.hasAttribute(name) -> Method To Check For Existence Of An Attribute
42 | // 2. elem.getAttribute(name) -> Method Used To Get The Value Of An Attribute
43 | // 3. elem.setAttribute(name, value) -> Method Used To Set The Value Of An Attribute
44 | // 4. elem.removeAttribute(name) -> Method Used To Remove The Attribute From Element
45 | // 5. elem.attributes -> Method To Get The Collection Of All Attributes
46 | // Data-* Attributes
47 | // 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
48 | // If An Element Has An Attribute Named "data-one" -> The Way To Access This Attribute Is : elem.dataset.one
49 |
50 |
51 | // let a = first.getAttribute("class")
52 | // console.log(a)
53 |
54 |
55 | // console.log(first.hasAttribute("class"))
56 | // console.log(first.hasAttribute("style"))
57 | // // first.setAttribute("hidden", "true")
58 | // first.setAttribute("class", "true sachin")
59 | // first.removeAttribute("class")
60 | // console.log(first.attributes)
61 | // console.log(first.dataset)
62 | // console.log(first.dataset.game)
63 | // console.log(first.dataset.player)
64 |
65 |
66 | // Always Add Custom Attribute With Data-_____
67 | // Data Attributes
68 | // data-one = "one" -> data-one -> One
69 | // data-game = "mario" -> data-game -> Mario
70 |
71 | // If Element Has A Attribute Named "data-one" -> The Way To Access This Attribute Is : elem.dataset.one
72 |
73 | // Insertion Method
74 |
75 | // There Are Three Way To Insert HTML Into The DOM
76 |
77 | // 1. innerHTML
78 |
79 | // let a = document.getElementsByTagName('div')[0]
80 | // a.innerHTML = a.innerHTML + 'Hello World! ';
81 |
82 |
83 | // 2. document.createElement()
84 | // let div = document.createElement('div');
85 | // div.innerHTML = 'Hello World! ';
86 | // a.appendChild(div);
87 | // div.className = "alert"
88 | // We Can Use For Loop In This Case
89 |
90 | // 3. document.createTextNode()
91 | // let div = document.createTextNode('This Is Text Node');
92 | // a.appendChild(div);
93 |
94 | // Node Insertion Method
95 | // 4. node.append(e) -> Append At The End Of Node
96 |
97 | // 5. node.prepend() -> Insert At The Beginning Of Node
98 |
99 | // 6. node.before() -> Insert Before Node
100 |
101 | // 7. node.after() -> Insert After Node
102 |
103 | // 8. node.replaceWith() -> Replace Node With Another Node
104 |
105 | // Insert Adjacent HTML / Text / Element
106 |
107 | // first.insertAdjacentHTML('beforebegin', 'beforebegin
');
108 | // first.insertAdjacentHTML('beforeend', 'beforeend
');
109 | // first.insertAdjacentHTML('afterbegin', 'afterbegin
');
110 | // first.insertAdjacentHTML('afterend', 'afterend
');
111 |
112 | // Node Removal
113 | // first.remove() -> Remove The Element
114 |
115 |
116 | // ClassName & ClassList
117 | // className -> Used To Add/Remove/Toggle A Class
118 | // classList -> Used To Add/Remove/Toggle A Class
119 | // first.className = "text-black red"
120 | // first.classList.remove("red") // Remove Karva
121 | // first.classList.add("red") // Add Karva
122 | // first.classList.toggle("red") // He To Hata Dega Nahi He to Laga Dega
123 | // first.classList.contains("red") // Check If Contain Or Not? -> True False
124 |
125 | // SetTimeout And SetInterval
126 |
127 | // setTimeout(function, , , )
128 | // setTimeOut -> Kuch Time Ke Bad Apni JS Ko excute Karna Hoga -> Excute The Js After Certain Time
129 | // clearTimeout -> To Clear The SetTimeout
130 | // setInterval -> In Certain Interval Of Time Hame Bar Bar Apni Js Ko Excute Karna Hoga -> Excute The Js After Certain Time(Interval)
131 | // setTimeout -> Is Function Ko Run Kardo Itne Time Ke Bad
132 |
133 | // alert("Hello")
134 | // let a = setTimeout(function() {
135 | // alert("I Am Inside Of SetTimeout")
136 | // }, 2000)
137 | // clearTimeout(a)
138 | // console.log(a) // Timer Id
139 |
140 | // let timerId = setInterval(function, , , )
141 | // Delay In millisecond
142 | // Timer Id Return Me Milti He
143 |
144 | // const sum = (a, b, c) => (){
145 | // console.log("Yes I Am Running " + (a + b + c))
146 | // a + b
147 | // }
148 |
149 | // setTimeout(sum, 1000, 1, 2, 7)
150 | // clearTimeout(timerId)
151 |
152 | // setInterval -> Bar Bar Kuch Time Ke Bad Run Karna
153 | // Syntex -> setInterval(function, , , )
154 |
155 | // Example:
156 | // let a = setInterval(function() {
157 | // console.log("I Am In SetInterval")
158 | // }, 3000)
159 |
160 |
161 | // clearInterval(a) -> To Clear The SetInterval
162 |
163 | // Browser Events
164 |
165 | // An Event Is A Signal That Something Has Happened.
166 | // All Dom Node Generate Such Signal
167 |
168 | // Mouse Events -> click, contextmenu, mouseover/mouseout, mousedown/mouseup, mousemove
169 |
170 | // Keyboard Events -> keydown and keyup
171 | // Form Element Events -> submit, focus
172 | // Document Events -> DOMContentLoaded
173 |
174 | // Click Me
175 |
176 | // Handling Events
177 | // elem.onclick = function(e){
178 | // alert("Hello World1!")
179 | // }
180 |
181 | // let a = document.getElementsByClassName("container")[0]
182 | // console.log(a)
183 | // a.onclick = () => {
184 | // let b = document.getElementsByClassName("container")[0]
185 | // b.innerHTML = "Hello World!"
186 | // }
187 |
188 | // If Onclick Js and HTML Me Likha Hai To Js Vala Priorty Hota Hai
189 |
190 | // Adding A Handler With JavaScript Overwrite The Existing Handler
191 |
192 | // Event Listener
193 |
194 | // addEventListener(event, handler) and removeEventListener(event, handler)
195 |
196 | // Handler Must Be Same While Removing It
197 |
198 | // addeventListener -> To Assign Multiple Handlers To An Event
199 |
200 | // let x = function(e) {
201 | // alert("Hello World1!")
202 | // }
203 | // let y = function(e) {
204 | // console.log(e) // Event Object -> Pointing To The Our Function
205 | // // console.log(e.target)
206 | // alert("Hello World2!")
207 | // }
208 | // btn.addEventListener('click', x)
209 |
210 | // btn.addEventListener('click', function(e) {
211 | // alert("Hello World2!")
212 | // })
213 |
214 | // btn.addEventListener('click', y)
215 |
216 | // let a = prompt("What is Your Favorite Number?");
217 | // if (a == "2") {
218 | // btn.removeEventListener('click', x)
219 | // }
220 |
221 | // 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
222 |
223 |
224 | // Event Object
225 |
226 | // 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
227 |
228 | // elem.onclick = function(event){
229 | // Code
230 | // }
231 |
232 | // event.type -> Event Type
233 | // event.currentTarget -> Element That Handled The Event
234 | // event.clientX/ event.clientY -> Coordinates Of Cursor
235 |
236 |
237 | // Practice Set
238 |
239 | // Q1 -> Create A Website Which Stores Bookmarks Of Your Favorite Website Using href
240 | // Ans: Ans On HTML File
241 | // Q2 -> Write A Program To Show Different Alerts When Different Buttons Are Clicked
242 | // Ans: Ans On HTML File
243 | // Q3 -> Create A Website Which Stores Bookmarks Of Your Favorite Website Using Event Listeners
244 | // document.getElementById("google").addEventListener("click", function() {
245 | // window.location = "https://www.google.com";
246 | // win.focus();
247 | // })
248 | // document.getElementById("fb").addEventListener("click", function() {
249 | // window.location = "https://www.facebook.com";
250 | // win.focus();
251 | // })
252 | // document.getElementById("twitter").addEventListener("click", function() {
253 | // window.location = "https://www.twitter.com";
254 | // win.focus();
255 | // })
256 | // document.getElementById("insta").addEventListener("click", function() {
257 | // window.location = "https://www.instagram.com";
258 | // win.focus();
259 | // })
260 |
261 |
262 | // Q4 -> Write A JavaScript Program To Keep fetching contents of a website (Every 5 Seconds)
263 |
264 | // setInterval(async function() {
265 | // let url = "https://jsonplaceholder.typicode.com/todos/1"
266 | // console.log(await fetchContent(url))
267 | // },3000)
268 |
269 | // const fetchContent = async (url) =>{
270 | // con = await fetch(url);
271 | // let a = await con.json()
272 | // return a;
273 | // }
274 |
275 | // Q5 -> Create A Glowing Bulb Effect Using ClassList Toggle Method In JavaScript
276 |
277 |
278 | // setInterval(async function(){
279 | // document.querySelector("#bulb").classList.toggle("bulb")
280 | // },300)
281 |
282 | // Clock
283 |
284 | // let a = new Date()
285 | // let h = a.getHours()
286 | // let m = a.getMinutes()
287 | // let s = a.getSeconds()
288 |
289 |
--------------------------------------------------------------------------------
/Ch-10-Network-Request-And-Storing-Data.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-10-Network-Request-And-Storing-Data.zip
--------------------------------------------------------------------------------
/Ch-10-Network-Request-And-Storing-Data/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-10-Network-Request-And-Storing-Data/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-10-Network-Request-And-Storing-Data/image.png
--------------------------------------------------------------------------------
/Ch-10-Network-Request-And-Storing-Data/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | replit
8 |
9 |
10 |
12 |
13 |
14 |
15 |
16 | Contests
17 |
19 |
20 |
21 |
22 |
38 |
39 |
40 |
41 |
42 |
Programming Contests
43 |
This is a simple hero unit, a simple jumbotron-style component for calling extra
44 | attention to featured content or information.
45 |
46 |
It uses utility classes for typography and spacing to space content out within the larger
47 | container.
48 |
Learn more
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
65 |
66 |
69 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/Ch-10-Network-Request-And-Storing-Data/script.js:
--------------------------------------------------------------------------------
1 | // Fetch API
2 | // The Fetch API provides a simple way to fetch resources (for example images, documents, or streams) over the internet
3 |
4 | // JavaScript Can Be Used To Send And Retrieve Information From The Network When Needed (AJAX)
5 |
6 | // AJAX Used Earlier -> Now JSON Is Widely Used
7 |
8 | // AJAX -> Asynchronous JavaScript And XML
9 |
10 | // Fetch API
11 |
12 | // Fetch Is Used To Get Data Over The Internet
13 |
14 | // let promise = fetch(URL, [options])
15 | // Without Option A GET Request Is Sent
16 |
17 | // Getting The Response Is A 2-Stage Process
18 |
19 | // 1. An Object Of Response Class Containing "Status" And "Ok" Properties
20 | // Status - The HTTP Status Code, eg 200
21 | // Ok - Boolean, True If The HTTP Status Code Is 200-299
22 |
23 | // 2. After That We Need To Call Another Method To Access The Body In Different Formats
24 |
25 | // Response.text() - Read The Response As Text
26 | // Response.json() - Parse The Response As JSON
27 |
28 | // Other Methods Include - Response.formData(), Response.blob(), Response.arrayBuffer()
29 |
30 | // Note - We Can Use Only One Body Method. For Example If We Have Used Response.text() Then We Cannot Use Response.json()
31 |
32 | // Response Headers
33 |
34 | // The Response Headers Are Available In Response.headers
35 |
36 | // Request Headers
37 | // To Set A Request Header In Fetch, We Can Use The Headers Option
38 |
39 | // let res = fetch(url, {
40 | // header: {
41 | // Authentication: 'Secret'
42 | // }
43 | // });
44 |
45 |
46 | // POST Request
47 |
48 | // let p = fetch("https://api.rainviewer.com/public/weather-maps.json")
49 | // p.then((response) => {
50 | // console.log(response.status)
51 | // console.log(response.ok)
52 | // console.log(response.headers)
53 | // return response.json()
54 | // }).then(data => {
55 | // console.log(data)
56 | // })
57 | // Why Two .then Is Mentioned Above?
58 | // Response Contain Two Properties - Status And Ok
59 | // Data Is The Actual Result Of The Request
60 |
61 | // POST Request
62 | // To Make Post Request, We Need To Use Fetch Options
63 | // Method -> HTTP Method, E.g POST
64 | // Body -> The Request Body
65 |
66 | // const createTodo = async (todo) => {
67 | // let options = {
68 | // method: "POST",
69 | // headers: {
70 | // "Content-type": "application/json"
71 | // },
72 | // body: JSON.stringify(todo),
73 | // }
74 | // let p = await fetch('https://jsonplaceholder.typicode.com/posts', options)
75 | // let response = await p.json()
76 | // return response
77 | // }
78 |
79 | // const getTodo = async (id) => {
80 | // let response = await fetch('https://jsonplaceholder.typicode.com/posts/' + id)
81 | // let r = await response.json()
82 | // return r
83 | // }
84 |
85 | // const mainFunc = async () => {
86 | // let todo = {
87 | // title: 'Harry2',
88 | // body: 'bhai2',
89 | // userId: 1100,
90 | // }
91 | // let todor = await createTodo(todo)
92 | // console.log(todor)
93 | // console.log(await getTodo(101))
94 | // }
95 |
96 | // mainFunc()
97 |
98 | // let response = await fetch('/url', {
99 | // method: 'POST',
100 | // headers: {
101 | // 'Content-Type': 'application/json'
102 | // },
103 | // body: JSON.stringify({
104 | // title: 'foo',
105 | // body: 'bar',
106 | // userId: 1,
107 | // })
108 | // })
109 |
110 | // let result = await response.json()
111 |
112 | // JavaScript Cookies
113 | // Cookies Are Small Strings Of Data Stored By The Client Side Stored In Browser
114 | // In JavaScript, Document.cookie Property Can Be Used To Access Cookies
115 |
116 | // 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.
117 |
118 | // We Can Also Access Cookies Using document.cookie Property
119 | // alert(document.cookie) -> Contain Key Value Pairs Decoded
120 |
121 | // Key Value Pair Are Separated By Delimited By ; -> Key = Pair;
122 |
123 | // Writing A Cookie
124 | // An Assignment To Document.cookie Is Treated Specially In A Way That Write Operation Doesn't Touch Other Cookie
125 |
126 | // document.cookie = "name=harry1122334400"
127 | // Updates Only Cookie Named User To Harry
128 |
129 | // Bahot Chota Sa Data Store Karneka Tarika
130 | // console.log(document.cookie)
131 | // document.cookie = "name=harry1122334400"
132 | // document.cookie = "name2=harry11223344002" // Set Call
133 | // document.cookie = "name=harry" // Old Is Updated
134 | // let key = prompt("enter your key")
135 | // let value = prompt("enter your value")
136 | // document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
137 | // console.log(document.cookie)
138 |
139 | // Encode URI Component -> This Function Encodes A Set Of Special Characters In A Way That The Component Can Be Decoded Using DecodeURI
140 |
141 | // This Function Helps Keep The Valid Formatting. It Is Used Like This
142 |
143 | // document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
144 |
145 | // This Way Spacial Character Are Encoded
146 |
147 | // Cookies Option
148 |
149 | // Cookies Have Several Options Which Can Be Provided After Key=Value To A Set Call Like This :
150 |
151 | // document.cookie = "user=harry;path=/a;expires=Tue,29 March 204"
152 | // path -> Which Domain The Cookie Will Be Available On
153 | // document.cookie = "user=harry;path=/a;expires=Tue,29 March 2041 12:00:33 GMT"
154 | // Set Only One Cookies With Path And Expires
155 | // document.cookies -> Can Set Only One Cookie At A Time Other Are Option
156 |
157 |
158 | // Path Option Makes The Cookie Available Only At The /a and /a/b ................ Path. -> Not Available At /b But Available At /a/b
159 | // Expires At -> Date When Cookie Will Be Expired. Time Stamp In GMT
160 |
161 | // Note :
162 | // 1. The Name And Value Pair After EncodeURI Component Can Be Up To 4KB
163 | // 2. Total No Of Cookies Per Domain Is Limited To Arbitrary Number Around 20+ (Exact Number Is Browser Dependent)
164 | // 3. Cookies Are Sent With Each Request To The Server, So The Server Can Learn Who Sent The Request
165 |
166 | // Local Storage
167 | // Local Storage Is Web Storage Object Which Are Not Sent To Server With Each Request
168 | // Data Survives Page Refresh And Even After Full Restart
169 |
170 | // These Are Method Provided By Local Storage
171 |
172 | // 1. localStorage.setItem(key, value) -> Store Key Value Pair Or Update The Value If Key Is Already Present
173 | // 2. localStorage.getItem(key) -> Get The Value By Key
174 | // 3. localStorage.removeItem(key) -> Remove The Key Value Pair
175 | // 4. localStorage.clear() -> Clear The Entire Local Storage
176 | // 5. localStorage.key(index) -> Get The Key On A Given Position
177 | // 6. localStorage.length -> The Number Of Stored Items
178 | // We Can Use Both Key And Value As String
179 |
180 | // let key = prompt("Enter key you want to set")
181 | // let value = prompt("Enter value you want to set")
182 |
183 | // localStorage.setItem(key, value)
184 |
185 | // console.log(`The value at ${key} is ${localStorage.getItem(key)}`)
186 |
187 | // if (key == "red" || key == "blue") {
188 | // localStorage.removeItem(key)
189 | // }
190 |
191 | // if (key == 0) {
192 | // localStorage.clear()
193 | // }
194 | // console.log(localStorage.length)
195 |
196 | // We Can Get And Set Values Like An Object
197 | // localStorage.one = 1
198 | // alert(localStorage.one)
199 | // delete localStorage.one
200 |
201 | // Note:
202 | // 1. Both Key And Value Must Be String
203 | // 2. We Can Use The Two JSON Methods To Store Objects In Local Storage
204 |
205 | // JSON.stringify(object) -> Converts Objects To JSON Strings
206 | // JSON.parse(string) -> Converts String To Objects (Must Be Valid JSON)
207 |
208 | // Session Storage
209 | // Session Storage Exists For Only One Session. Data Survives Refresh But Not Close Of Browser
210 |
211 | // Used Less As Compared To Local Storage
212 | // Properties And Method Are Same As Local Storage But:
213 | // 1. Session Storage Data Survives Page Refresh But Not Close Of Browser
214 | // It Exists Only Within The Current Browser Tab. Another Tab With Same Page Will Have Empty Session Storage
215 |
216 | // 2. The Data Survives Page Refresh, But Not Closing / Opening Of Browser
217 |
218 | // Storage Event
219 | // When The Data Gets Updated In Local Storage Or Session Storage, Storage Event Triggered With These Properties:
220 | // 1. key -> The Key
221 | // 2. oldValue -> Previous Value
222 | // 3. newValue -> New Value
223 | // 4. url -> Page URL
224 | // 5. storageArea -> local or session
225 |
226 | // We Can Listen The OnStorage Event Of Window Which Is Triggered When Updates Are Made To The Same Storage From Other Documents
227 |
228 | // sessionStorage.getItem("name")
229 | // sessionStorage.clear()
230 | // sessionStorage.removeItem("name")
231 | // sessionStorage.setItem("name", "harry")
232 | // sessionStorage.removeItem("name")
233 |
234 | // Dusri Tab Dusra Page Different Session Storage
235 |
236 | // window.onstorage = (e) => {
237 | // alert("changed")
238 | // console.log(e)
239 | // }
240 |
241 | // Practice Set
242 |
243 | // Q1 Use a Free API From The Internet And Feed Your App With Live Data
244 |
245 | // Q2 Create A Note Saving App Which Stores Your Note To localStorage
246 |
247 | // Q3 Repeat Q2 And Fetch The Note Which User Entered In The Previous Question
248 |
249 | // Q4 Delete The Note In The Previous Question
250 |
251 |
252 | let url = "https://kontests.net/api/v1/all"
253 | let response = fetch(url)
254 | response.then((v) => {
255 | return v.json()
256 | }).then((contests) => {
257 | console.log(contests)
258 | ihtml = ""
259 | for (item in contests) {
260 | console.log(contests[item])
261 | ihtml += `
262 |
263 |
264 |
265 |
${contests[item].name}
266 |
Status is ${contests[item].status} and site is ${contests[item].site}
267 |
In 24 Hours? ${contests[item].in_24_hours}
268 |
Starts at: ${contests[item].start_time}
269 |
Starts at: ${contests[item].end_time}
270 | Visit Contest
271 |
272 |
273 | `
274 | }
275 | cardContainer.innerHTML = ihtml
276 | })
277 |
278 | /* ******************* NOTES APP (REMAINING QUESTIONS OF PRACTICE SET) *********** */
279 | // let n = localStorage.getItem("note")
280 | // alert("Your note is " + n)
281 |
282 | // let a = prompt("Enter your note")
283 | // if (a) {
284 | // localStorage.setItem("note", a)
285 | // }
286 |
287 | // let c = confirm("Do you want to delete your note?")
288 | // if (c) {
289 | // localStorage.removeItem("note")
290 | // alert("Note deleted successfully!")
291 | // }
292 |
--------------------------------------------------------------------------------
/Ch-10-Network-Request-And-Storing-Data/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | }
--------------------------------------------------------------------------------
/Ch-11-Object-Oriented-Programing.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-11-Object-Oriented-Programing.zip
--------------------------------------------------------------------------------
/Ch-11-Object-Oriented-Programing/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-11-Object-Oriented-Programing/Readme.md:
--------------------------------------------------------------------------------
1 |
2 | **Define a Constructor Function:**
3 |
4 | ```javascript
5 | function Person(name, age) {
6 | this.name = name;
7 | this.age = age;
8 | }
9 | ```
10 |
11 | **Add a Method to the Constructor Function's Prototype:**
12 |
13 | ```javascript
14 | Person.prototype.sayHello = function() {
15 | console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
16 | };
17 | ```
18 |
19 | **Create a New Object Using the Constructor Function:**
20 |
21 | ```javascript
22 | const person1 = new Person("Alice", 30);
23 | ```
24 |
25 | **Call the Method on the Object:**
26 |
27 | ```javascript
28 | person1.sayHello(); // Output: "Hello, my name is Alice and I'm 30 years old."
29 | ```
30 |
31 | ---
32 |
33 | ## Prototypal Inheritance.
34 |
35 |
36 | ```javascript
37 | // Define a constructor function
38 | function Person(name, age) {
39 | this.name = name;
40 | this.age = age;
41 | }
42 |
43 | // Add a method to the constructor function's prototype
44 | Person.prototype.sayHello = function() {
45 | console.log("Hello, my name is " + this.name + " and I'm " + this.age + " years old.");
46 | };
47 |
48 | // Create a new object using the constructor function
49 | var person1 = new Person("Alice", 30);
50 |
51 | // Call the method on the object
52 | person1.sayHello(); // output: "Hello, my name is Alice and I'm 30 years old.
53 | ```
54 |
55 | **Object-Oriented Programming in JavaScript with Examples [Updated 2024]**
56 |
57 | 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.
58 |
59 | This guide explores the core principles of OOP in JavaScript with practical examples.
60 |
61 | ### Fundamentals of OOP in JavaScript
62 |
63 | 1. **Objects and Classes**
64 | - An object in JavaScript is a standalone entity with properties and a type.
65 |
66 | ```javascript
67 | const dog = {
68 | breed: 'Labrador',
69 | color: 'black',
70 | bark() {
71 | console.log('Woof!');
72 | }
73 | };
74 | dog.bark(); // Output: Woof!
75 | ```
76 |
77 | - Classes, introduced in ES6, serve as templates for creating objects.
78 |
79 | ```javascript
80 | class Animal {
81 | constructor(name) {
82 | this.name = name;
83 | }
84 | speak() {
85 | console.log(`${this.name} makes a noise.`);
86 | }
87 | }
88 | const animal = new Animal('Dog');
89 | animal.speak(); // Output: Dog makes a noise.
90 | ```
91 |
92 | 2. **Encapsulation**
93 | - Encapsulation involves hiding an object's internal representation from the outside.
94 |
95 | ```javascript
96 | class Car {
97 | constructor(brand) {
98 | this._brand = brand;
99 | }
100 | get brand() {
101 | return this._brand;
102 | }
103 | set brand(newBrand) {
104 | this._brand = newBrand;
105 | }
106 | }
107 | const myCar = new Car('Ford');
108 | console.log(myCar.brand); // Output: Ford
109 | myCar.brand = 'BMW';
110 | console.log(myCar.brand); // Output: BMW
111 | ```
112 |
113 | 3. **Inheritance**
114 | - Inheritance allows a class to inherit properties and methods from another class.
115 |
116 | ```javascript
117 | class Animal {
118 | constructor(name) {
119 | this.name = name;
120 | }
121 | speak() {
122 | console.log(`${this.name} makes a noise.`);
123 | }
124 | }
125 | class Dog extends Animal {
126 | speak() {
127 | console.log(`${this.name} barks.`);
128 | }
129 | }
130 | const d = new Dog('Mitzie');
131 | d.speak(); // Output: Mitzie barks.
132 | ```
133 |
134 | 4. **Polymorphism**
135 | - Polymorphism enables objects of different classes to be treated as instances of a common superclass.
136 |
137 | ```javascript
138 | class Animal {
139 | speak() {
140 | console.log('Animal speaks');
141 | }
142 | }
143 | class Cat extends Animal {
144 | speak() {
145 | console.log('Meow');
146 | }
147 | }
148 | class Dog extends Animal {
149 | speak() {
150 | console.log('Woof');
151 | }
152 | }
153 | function makeAnimalSpeak(animal) {
154 | animal.speak();
155 | }
156 | makeAnimalSpeak(new Cat()); // Output: Meow
157 | makeAnimalSpeak(new Dog()); // Output: Woof
158 | ```
159 |
160 | 5. **Abstraction**
161 | - Abstraction involves creating simple models to represent complex real-world objects.
162 |
163 | ```javascript
164 | class Vehicle {
165 | startEngine() {
166 | console.log('Engine started');
167 | }
168 | stopEngine() {
169 | console.log('Engine stopped');
170 | }
171 | }
172 | class Car extends Vehicle {
173 | startEngine() {
174 | console.log('Car engine started');
175 | }
176 | }
177 | const myCar = new Car();
178 | myCar.startEngine(); // Output: Car engine started
179 | ```
180 |
181 | ### Advanced OOP Concepts in JavaScript
182 |
183 | 6. **Constructors and the new Keyword**
184 | - Constructors are special functions for creating and initializing objects.
185 |
186 | ```javascript
187 | class Person {
188 | constructor(name, age) {
189 | this.name = name;
190 | this.age = age;
191 | }
192 | }
193 | const person = new Person('Alice', 25);
194 | console.log(person); // Output: Person { name: 'Alice', age: 25 }
195 | ```
196 |
197 | 7. **Methods — Instance, Static, and Prototype Methods**
198 | - Methods in JavaScript can be instance, static, or prototype methods.
199 |
200 | ```javascript
201 | class Rectangle {
202 | constructor(width, height) {
203 | this.width = width;
204 | this.height = height;
205 | }
206 | // Instance method
207 | getArea() {
208 | return this.width * this.height;
209 | }
210 | // Static method
211 | static compareArea(rect1, rect2) {
212 | return rect1.getArea() - rect2.getArea();
213 | }
214 | }
215 | const rect1 = new Rectangle(5, 8);
216 | const rect2 = new Rectangle(6, 7);
217 | console.log(Rectangle.compareArea(rect1, rect2)); // Output: -2
218 | ```
219 |
220 | 8. **Getters and Setters**
221 | - Getters and setters allow you to define Object Accessors (Computed Properties).
222 |
223 | ```javascript
224 | class Person {
225 | constructor(firstName, lastName) {
226 | this.firstName = firstName;
227 | this.lastName = lastName;
228 | }
229 | get fullName() {
230 | return `${this.firstName} ${this.lastName}`;
231 | }
232 | set fullName(name) {
233 | [this.firstName, this.lastName] = name.split(' ');
234 | }
235 | }
236 | const person = new Person('John', 'Doe');
237 | console.log(person.fullName); // Output: John Doe
238 | person.fullName = 'Jane Smith';
239 | console.log(person.fullName); // Output: Jane Smith
240 | ```
241 |
242 | 9. **Inheritance with extends and super**
243 | - The `extends` keyword is used to create a child class from a parent class.
244 |
245 | ```javascript
246 | class Shape {
247 | constructor(name) {
248 | this.name = name;
249 | }
250 | move() {
251 | console.log(`${this.name} moved`);
252 | }
253 | }
254 | class Circle extends Shape {
255 | constructor(radius) {
256 | super('Circle');
257 | this.radius = radius;
258 | }
259 | }
260 | const myCircle = new Circle(5);
261 | myCircle.move(); // Output: Circle moved
262 | ```
263 |
264 | ### Object-Oriented vs. Functional Programming in JavaScript
265 |
266 | **Differences Between OOP and Functional Programming:**
267 | - **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.
268 | - **Methodology:** OOP models real-world entities using objects and classes, while functional programming focuses on computation and avoids changing state.
269 | - **Code Reusability:** In OOP, reusability comes through inheritance and polymorphism. Functional programming achieves reusability through functions and higher-order functions.
270 |
271 | **When to Use OOP or Functional Programming:**
272 | - **Use OOP when:**
273 | - You’re dealing with a complex system with clearly defined types and relationships.
274 | - Your application’s state changes frequently and needs cohesive management.
275 | - You prefer a modular, structured approach to organizing code.
276 |
277 | - **Use Functional Programming when:**
278 | - You need a system with operations that don’t depend on or alter the state.
279 | - Your focus is on data flow and transformations.
280 | - You aim for code that’s easy to test and reason about, thanks to its immutability and purity.
281 |
282 | ### Conclusion:
283 | 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.
284 |
285 | ### Prototypal Inheritance.
286 |
287 | 
288 |
289 |
290 | Here's how you can approach each of these practice problems:
291 |
292 | ### Q1: Create a Class to Create a Complex Number. Create a Constructor to Set the Real and Imaginary Parts.
293 | ```javascript
294 | class ComplexNumber {
295 | constructor(real, imaginary) {
296 | this.real = real;
297 | this.imaginary = imaginary;
298 | }
299 | }
300 |
301 | // Example usage:
302 | let num1 = new ComplexNumber(3, 4); // Complex number: 3 + 4i
303 | console.log(`Complex Number: ${num1.real} + ${num1.imaginary}i`);
304 | ```
305 |
306 | ### Q2: Write a Method to Add Two Complex Numbers in the Above Class.
307 | ```javascript
308 | class ComplexNumber {
309 | constructor(real, imaginary) {
310 | this.real = real;
311 | this.imaginary = imaginary;
312 | }
313 |
314 | add(otherComplex) {
315 | return new ComplexNumber(
316 | this.real + otherComplex.real,
317 | this.imaginary + otherComplex.imaginary
318 | );
319 | }
320 | }
321 |
322 | // Example usage:
323 | let num1 = new ComplexNumber(3, 4);
324 | let num2 = new ComplexNumber(1, 2);
325 | let sum = num1.add(num2);
326 | console.log(`Sum: ${sum.real} + ${sum.imaginary}i`);
327 | ```
328 |
329 | ### Q3: Create a Class `Student` from a Class `Human`. Override a Method and See Changes.
330 | ```javascript
331 | class Human {
332 | speak() {
333 | console.log("Hello, I am a human.");
334 | }
335 | }
336 |
337 | class Student extends Human {
338 | speak() {
339 | console.log("Hello, I am a student.");
340 | }
341 | }
342 |
343 | // Example usage:
344 | let person = new Human();
345 | person.speak(); // Output: "Hello, I am a human."
346 |
347 | let student = new Student();
348 | student.speak(); // Output: "Hello, I am a student."
349 | ```
350 |
351 | ### Q4: See if `Student` is an Instance of `Human` Using `instanceof` Keyword.
352 | ```javascript
353 | console.log(student instanceof Human); // Output: true
354 | console.log(student instanceof Student); // Output: true
355 | console.log(person instanceof Student); // Output: false
356 | ```
357 |
358 | ### Q5: Use Getters and Setters to Set and Get the Real and Imaginary Parts of the Complex Number.
359 | ```javascript
360 | class ComplexNumber {
361 | constructor(real, imaginary) {
362 | this._real = real;
363 | this._imaginary = imaginary;
364 | }
365 |
366 | get real() {
367 | return this._real;
368 | }
369 |
370 | set real(value) {
371 | this._real = value;
372 | }
373 |
374 | get imaginary() {
375 | return this._imaginary;
376 | }
377 |
378 | set imaginary(value) {
379 | this._imaginary = value;
380 | }
381 | }
382 |
383 | // Example usage:
384 | let num = new ComplexNumber(5, 6);
385 | console.log(`Before: ${num.real} + ${num.imaginary}i`);
386 |
387 | num.real = 7; // Using setter
388 | num.imaginary = 8; // Using setter
389 |
390 | console.log(`After: ${num.real} + ${num.imaginary}i`); // Using getter
391 | ```
392 |
393 | ### Summary:
394 | - **Q1**: We defined a `ComplexNumber` class with a constructor to initialize the real and imaginary parts.
395 | - **Q2**: Added a method to sum two complex numbers.
396 | - **Q3**: Demonstrated inheritance by creating a `Student` class from `Human` and overriding a method.
397 | - **Q4**: Used the `instanceof` keyword to check if an object is an instance of a particular class.
398 | - **Q5**: Implemented getters and setters to access and modify the real and imaginary parts of the complex number.
--------------------------------------------------------------------------------
/Ch-11-Object-Oriented-Programing/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-11-Object-Oriented-Programing/image.png
--------------------------------------------------------------------------------
/Ch-11-Object-Oriented-Programing/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | replit
8 |
9 |
10 |
11 |
12 | Hello world
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ch-11-Object-Oriented-Programing/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | }
--------------------------------------------------------------------------------
/Ch-12-Advanced-JavaScript.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-12-Advanced-JavaScript.zip
--------------------------------------------------------------------------------
/Ch-12-Advanced-JavaScript/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-12-Advanced-JavaScript/Readme.md:
--------------------------------------------------------------------------------
1 | ### JavaScript Closures: An Overview
2 |
3 | **Definition**:
4 | 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.
5 |
6 | **Key Concepts**:
7 | 1. **Lexical Environment**:
8 | - 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.
9 | - The environment in which a function was declared is known as its *lexical environment*.
10 |
11 | 2. **Inner Functions**:
12 | - 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.
13 | - The inner function has access to the variables declared in the outer function, even after the outer function has finished executing.
14 |
15 | 3. **Persistent Data**:
16 | - Closures allow you to create functions with persistent data. The inner function can "remember" the state of variables from its outer function's scope.
17 |
18 | **Example**:
19 | ```javascript
20 | function outerFunction() {
21 | let counter = 0; // local variable to outerFunction
22 |
23 | function innerFunction() {
24 | counter++; // modifying outer function's variable
25 | console.log(counter);
26 | }
27 |
28 | return innerFunction;
29 | }
30 |
31 | const incrementCounter = outerFunction();
32 | incrementCounter(); // Output: 1
33 | incrementCounter(); // Output: 2
34 | incrementCounter(); // Output: 3
35 | ```
36 | **Explanation**:
37 | - `outerFunction` creates a local variable `counter` and an `innerFunction` that increments and logs the counter.
38 | - `innerFunction` is returned and assigned to `incrementCounter`.
39 | - Even though `outerFunction` has finished executing, `incrementCounter` still has access to the `counter` variable because of the closure.
40 |
41 | **Uses of Closures**:
42 | 1. **Data Privacy**:
43 | - Closures can be used to create private variables in JavaScript.
44 | - This is a common pattern for encapsulating data and preventing it from being modified directly.
45 |
46 | ```javascript
47 | function createCounter() {
48 | let count = 0;
49 | return {
50 | increment: function() {
51 | count++;
52 | return count;
53 | },
54 | decrement: function() {
55 | count--;
56 | return count;
57 | },
58 | getCount: function() {
59 | return count;
60 | }
61 | };
62 | }
63 |
64 | const counter = createCounter();
65 | console.log(counter.increment()); // Output: 1
66 | console.log(counter.decrement()); // Output: 0
67 | console.log(counter.getCount()); // Output: 0
68 | ```
69 |
70 | 2. **Callbacks and Event Handlers**:
71 | - Closures are frequently used in asynchronous programming, such as when setting up event handlers or dealing with callbacks.
72 |
73 | ```javascript
74 | function setup() {
75 | let name = "Mozilla";
76 | document.getElementById("btn").addEventListener("click", function() {
77 | alert("Hello, " + name);
78 | });
79 | }
80 | setup();
81 | ```
82 |
83 | 3. **Functional Programming**:
84 | - In functional programming, closures are used to create higher-order functions, partially apply functions, or maintain state.
85 |
86 | **Common Pitfalls**:
87 | 1. **Memory Leaks**:
88 | - Closures can inadvertently cause memory leaks if not handled properly, as they retain references to their lexical scope even if not needed anymore.
89 |
90 | 2. **Overuse**:
91 | - Overusing closures can lead to complex and hard-to-maintain code. They should be used judiciously and with clear intent.
92 |
93 | **Conclusion**:
94 | - 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.
95 | - They are widely used in various programming patterns and can be essential for creating private variables, handling callbacks, and more.
96 | - Understanding closures is crucial for mastering JavaScript, especially when dealing with asynchronous code or implementing advanced functional programming techniques.
--------------------------------------------------------------------------------
/Ch-12-Advanced-JavaScript/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | replit
8 |
9 |
10 |
11 |
12 | Hello world
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ch-12-Advanced-JavaScript/script.js:
--------------------------------------------------------------------------------
1 | // IIFE -> Immediately Invoked Function Expression
2 |
3 | // IIFE Is A JavaScript Function That Runs As Soon As It Is Defined
4 | // (function() {
5 | // console.log("IIFE");
6 | // })();
7 |
8 | // // It is used to avoid polluting the global namespace, execute an async-await, etc.
9 |
10 | // let a = () => {
11 | // return new Promise((resolve, reject) => {
12 | // setTimeout(() => {
13 | // resolve(456)
14 | // }, 4000)
15 | // })
16 | // }
17 |
18 | // (async () => {
19 | // let b = await a()
20 | // console.log(b)
21 | // let c = await a()
22 | // console.log(c)
23 | // let d = await a()
24 | // console.log(d)
25 | // })()
26 |
27 |
28 | // console.log(d) // Throws error
29 |
30 | // Destructuring And Spread Operator
31 | // Destructuring Assignment Is Used To Unpack Values From An Array, Or Properties From An Object, Into Dedicated Variables, In JavaScript.
32 |
33 | // let arr = [3, 5, 8, 9, 12, 14]
34 | // No need to do this:
35 | // let a = arr[0]
36 | // let b = arr[1]
37 | // let [a, b, c, d, ...rest] = arr
38 | // console.log(a, b, c, d, rest)
39 | // let [a, , b, ...rest] = arr
40 | // console.log(a, b, rest)
41 | // let { a, b } = { a: 1, b: 5 }
42 | // console.log(a, b)
43 |
44 | // [10, x,....rest] =[10, 20, 30, 40, 50, 60]
45 | // x will be 20 rest will be [30, 40, 50, 60]
46 |
47 | // Spread Operator
48 |
49 | // 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)
50 | // let arr1 = [3, 5, 8]
51 | // let obj1 = { ...arr1 }
52 | // console.log(obj1)
53 |
54 | // function sum(v1, v2, v3) {
55 | // return v1 + v2 + v3
56 | // }
57 |
58 | // console.log(sum(...arr1))
59 |
60 | // let obj2 = {
61 | // name: "Harry",
62 | // company: "Company xyz",
63 | // address: "XYZ"
64 | // }
65 |
66 | // console.log({ ...obj2, name: "John", company: "ABC" })
67 | // console.log({ name: "John", company: "ABC", ...obj2 }) // This will print the obj2 object without changing any values
68 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
69 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
70 |
71 | // Local, Global And Function Scope In JavaScript
72 | // var -> Global Scope
73 | // let and const -> Block Scope
74 | // Function Scope -> The variable declared inside a function, becomes local to the function.
75 |
76 | // let p = 9
77 | // function ax() {
78 | // let a = 8;
79 | // console.log(p)
80 | // console.log(a)
81 | // }
82 |
83 | // ax()
84 | // console.log(p)
85 | // console.log(a)
86 |
87 |
88 | // Hoisting In JavaScript
89 | // Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution
90 |
91 | // let a;
92 | // Following two lines will run successfully due to JavaScript hoisting
93 | // console.log(a)
94 | // greet()
95 | // var greet = function() {
96 | // console.log("Good morning")
97 | // }
98 |
99 | // var a = 9; // Declaration hoisted to the top but initialization is not
100 | // console.log(a)
101 |
102 | // Hoisting With Let And Var
103 | // let and const are not hoisted
104 | // console.log(num);
105 | // let num = 6; -> Throws an error
106 | // var num = 6; -> Doesn't throw an error
107 | // const num = 6; -> Throws an error
108 |
109 | // Function Expression And Class Expression Are Not Hoisted
110 | // Function Expression Me = Sign Ata He
111 |
112 | // Closer Set
113 |
114 | // A Closer Is A Function With Lexical Environment
115 |
116 | // function init() {
117 | // var name = 'Mozilla'; // name is a local variable created by init
118 | // function displayName() {
119 | // // displayName() is the inner function, a closure
120 | // console.log(name); // use variable declared in the parent function
121 | // }
122 | // name = "Harry"
123 | // return displayName;
124 | // }
125 | // let c = init();
126 | // c()
127 |
128 |
129 | // function returnFunc() {
130 | // const x = () => {
131 | // let a = 1
132 | // console.log(a)
133 | // const y = () => {
134 | // // let a = 2
135 | // console.log(a)
136 | // const z = () => {
137 | // // let a = 3
138 | // console.log(a)
139 | // }
140 | // z()
141 | // }
142 | // a = 999
143 | // y()
144 | // }
145 | // return x
146 | // }
147 |
148 | // let a = returnFunc()
149 | // a()
150 |
151 | // Closure -> Function + Its Lexical Environment
152 | // Reference Milta He
153 |
154 | // Lexical Environment -> The Environment Of The Function -> Mere Pass Nahi He To Mere Pass Ka Environment Me Ase Check Karega
155 |
156 | // Arrow Function
157 |
158 | // const sayHello = name => {
159 | // console.log("greeting" + " " + name)
160 | // console.log("hi")
161 | // }
162 |
163 | // const x = {
164 | // name: "Harry",
165 | // role: "Js Developer",
166 | // exp: 30,
167 | // show: function() {
168 | // // let that = this
169 | // // console.log(this)
170 | // setTimeout(() => {
171 | // // console.log(`The name is ${that.name}\nThe role is ${that.role}`)
172 | // console.log(`The name is ${this.name}\nThe role is ${this.role}`)
173 | // }, 2000)
174 | // }
175 | // }
176 | // sayHello("Harry", "Good Afternoon")
177 | // console.log(x.name, x.exp)
178 | // x.show()
179 |
180 | // Arrow Function Uses Lexical This
181 |
182 | // Practice Set
183 |
184 | // const a = async (text, n = 2) => {
185 | // return new Promise((resolve, reject) => {
186 | // setTimeout(() => {
187 | // resolve(text)
188 | // }, 1000 * n)
189 | // })
190 | // }
191 |
192 | // (
193 | // async () => {
194 | // let text = await a("Hello")
195 | // console.log(text)
196 | // text = await a("World")
197 | // console.log(text)
198 | // }
199 | // )()
200 |
201 | // function sum(a, b, c) {
202 | // return a + b + c
203 | // }
204 |
205 | // let x = [1, 3, 5]
206 | // console.log(sum(...x));
207 |
208 | // (async () => {
209 | // let text = await a("I am resolving after 1 second", 1)
210 | // console.log(text)
211 | // text = await a("I am resolving after 4 seconds", 4)
212 | // console.log(text)
213 | // }
214 | // )()
215 |
216 | // function simpleInterest(p, r, t) {
217 | // return (p * r * t) / 100;
218 | // }
219 |
220 | // console.log(simpleInterest(100, 5, 1))
221 |
222 | // Regex Expression Or Regular Expression
223 | // https://regexr.com/
224 | // const regex = /(Harry){2}/gi
225 | // const text = "Harryharry is a very very nice awesome nice very boy"
226 | // console.log(text.replace(regex, "VERY"))
227 |
228 | // Event Loop
229 |
230 | // Asynchronous CallBack
231 | // Sometimes the JavaScript code can take a lot of time and this can block the
232 | // page re render
233 | // JavaScript has asynchronous callbacks for non blocking behavior
234 | // JavaScript runtime can do only one thing at a time
235 | // Browser gives us other things which work along with the runtime like Web
236 | // APIs.
237 | // In node.js these are available as C++ APIs
238 |
239 | // setTimeout(function timer() {
240 | // console.log('You clicked the button!');
241 | // }, 2000);
242 |
243 | // console.log("Hi!");
244 |
245 | // setTimeout(function timeout() {
246 | // console.log("Click the button!");
247 | // }, 5000);
248 |
249 | // console.log("Welcome to loupe.");
250 |
251 | // Task Queue
252 | // JavaScript can do only one thing at a time
253 | // The rest are queued to the task queue waiting to be executed
254 | // When we run setTimeout, webapis will run a timer and push the function
255 | // provided to setTimeout to the task queue once the timer evis
256 | // These tasks will be pushed to the stack where they can executed
257 |
258 | // Event Loop
259 |
260 | // JavaScript has a runtime model based on an event loop, which is responsible
261 | // for executing the code, collecting and processing events, and executing queued
262 | // sub-tasks
263 | // The event loop pushes the tasks from the task queue to the call stack
264 | // setTimeout(func1, 0) can be used to defer a function until all the pending tasks
265 | // (so far) have been executed
266 | // We can see how these things work in action by visiting
267 | // For Understanding Call Stack In Js :http://latentflip.com/loupe/
268 |
269 | // Module In JS
270 |
271 |
272 | // const hello = ()=>{
273 | // console.log("Hello Harry")
274 | // }
275 |
276 | // const ahello = (name)=>{
277 | // console.log("Hello " + name)
278 | // }
279 |
280 | // module.exports = {hello, ahello};// same as below line
281 | // // module.exports = {hello: hello, ahello: ahello};
282 |
283 | // // ES6 Modules
284 | // export const hello = ()=>{
285 | // console.log("Hello Harry")
286 | // }
287 |
288 | // export const ahello = (name)=>{
289 | // console.log("Hello " + name)
290 | // }
291 |
292 | // const harry = ()=>{
293 | // console.log("Hello " + "Harry")
294 | // }
295 |
296 | // export default harry;
297 |
--------------------------------------------------------------------------------
/Ch-12-Advanced-JavaScript/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | }
--------------------------------------------------------------------------------
/Ch-4-String.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-4-String.zip
--------------------------------------------------------------------------------
/Ch-4-String/Readme.md:
--------------------------------------------------------------------------------
1 | ```
2 | // String
3 |
4 | // 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.
5 |
6 | // String are Used To Store And Manipulate Text
7 |
8 | // String -> Collection Of Characters
9 |
10 | // Single Quotes -> let name = 'dp';
11 | // Double Quotes -> let name = "dp";
12 |
13 | let name = "dp";
14 | // console.log(name[3]); -> undefined
15 |
16 |
17 | // Template Literals
18 |
19 | // After ES6 -> Template Literals Came In Use -> Use Back Tic
20 |
21 | let boy1 = "hmm"
22 | let boy2 = 'ok'
23 |
24 | // Print Hmm nice ok
25 | // let sentence = `boy1 "nice" 'is' boy2` -> We a Make String -> Use Single Or Double Quotes Both Usage Possible If String Made Through Back Tic
26 |
27 | // String Interpolation
28 | let sentence = `${boy1} nice ${boy2}`
29 | console.log(sentence)
30 | // hmm nice ok
31 |
32 | let fruit = `Bana\'na` -> Bana'na
33 | console.log(fruit)
34 |
35 | // \' -> Escape Character -> Count As One Character
36 | // \n -> New Line
37 | // \t -> Tab
38 | // \r -> Carrige Return
39 |
40 |
41 | // String Method & Properties
42 | // Accessing Characters:
43 | // Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0.
44 |
45 | // const message = 'Hello';
46 | // console.log(message[0]); // Output: H
47 | // console.log(message[3]); // Output: l
48 |
49 | // String Concatenation:
50 | // Strings can be concatenated using the + operator or the concat() method.
51 |
52 |
53 | // const firstName = 'John';
54 | // const lastName = 'Doe';
55 | // const fullName = firstName + ' ' + lastName;
56 | // console.log(fullName); // Output: John Doe
57 |
58 | // // Using concat()
59 | // const message = 'Hello, ';
60 | // const name = 'John';
61 | // const greeting = message.concat(name);
62 | // console.log(greeting); // Output: Hello, John
63 |
64 | // Finding Substrings:
65 | // 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.
66 |
67 | // const message = 'Hello, world!';
68 | // console.log(message.indexOf('world')); // Output: 7
69 | // console.log(message.indexOf('open')); // Output: -1
70 |
71 |
72 | // Extracting Substrings:
73 | // The slice() method extracts a portion of a string based on the start and end indexes.
74 |
75 | // const message = 'Hello, world!';
76 | // console.log(message.slice(0, 5)); // Output: Hello
77 | // console.log(message.slice(7)); // Output: world!
78 |
79 | // Replacing Substrings:
80 | // The replace() method replaces a specified substring with another substring.
81 |
82 | // const message = 'Hello, John!';
83 | // console.log(message.replace('John', 'Alice')); // Output: Hello, Alice!
84 |
85 | // Splitting Strings:
86 | // The split() method splits a string into an array of substrings based on a specified delimiter.
87 |
88 | // const message = 'Hello, World!';
89 | // console.log(message.split(' ')); // Output: ["Hello,", "World!"]
90 |
91 |
92 | // Checking if a String Contains a Substring:
93 | // The includes() method checks if a string contains a specified substring and returns true or false.
94 |
95 | // const message = 'Hello, World!';
96 | // console.log(message.includes('World')); // Output: true
97 | // console.log(message.includes('open')); // Output: false
98 |
99 | // String Length:
100 | // The length property returns the number of characters in a string.
101 |
102 | // const message = 'Hello, world!';
103 | // console.log(message.length); // Output: 13
104 |
105 | // String Slice:
106 | // The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string.
107 |
108 | // const message = 'Hello, world!';
109 | // console.log(message.slice(7)); // Output: world!
110 | // console.log(message.slice(0, 5)); // Output: Hello
111 |
112 |
113 | // String Substring:
114 | // The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string.
115 |
116 |
117 | // const message = 'Hello, world!';
118 | // console.log(message.substring(7)); // Output: world!
119 | // console.log(message.substring(0, 5)); // Output: Hello
120 |
121 |
122 | // String Substr:
123 | // The substr() method extracts a portion of a string based on the start index and length. It returns a new string.
124 |
125 |
126 | // const message = 'Hello, world!';
127 | // console.log(message.substr(7)); // Output: world!
128 | // console.log(message.substr(0, 5)); // Output: Hello
129 |
130 | // String Replace:
131 |
132 | // The replace() method replaces a specified substring with another substring. It returns a new string.
133 |
134 | // const message = 'Hello, John!';
135 | // console.log(message.replace('John', 'Alice')); // Output: Hello, Alice!
136 |
137 | // String ReplaceAll:
138 | // The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021)
139 |
140 |
141 | // const message = 'Hello, John! John is a good guy.';
142 | // console.log(message.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy.
143 |
144 | // String toUpperCase and toLowerCase:
145 | // The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string.
146 |
147 |
148 | // const message = 'Hello, world!';
149 | // console.log(message.toUpperCase()); // Output: HELLO, WORLD!
150 | // console.log(message.toLowerCase()); // Output: hello, world!
151 |
152 |
153 | // String Concatenation:
154 | // The concat() method concatenates two or more strings and returns a new string.
155 |
156 |
157 | // const firstName = 'John';
158 | // const lastName = 'Doe';
159 | // console.log(firstName.concat(' ', lastName)); // Output: John Doe
160 |
161 |
162 | // String Trim:
163 | // The trim() method removes whitespace from both ends of a string and returns a new string.
164 |
165 | // const message = ' Hello, world! ';
166 | // console.log(message.trim()); // Output: Hello, world!
167 |
168 |
169 | // String TrimStart and TrimEnd:
170 | // 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)
171 |
172 | // const message = ' Hello, world! ';
173 | // console.log(message.trimStart()); // Output: Hello, world!
174 | // console.log(message.trimEnd()); // Output: Hello, world!
175 |
176 | // String PadStart and PadEnd:
177 | // 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)
178 |
179 | // const message = 'Hello';
180 | // console.log(message.padStart(10, '*')); // Output: *****Hello
181 | // console.log(message.padEnd(10, '-')); // Output: Hello-----
182 |
183 |
184 | // String CharAt and CharCodeAt:
185 | // The charAt() method returns the character at a specified index in a string.
186 | // The charCodeAt() method returns the Unicode value of the character at a specified index in a string.
187 |
188 | // const message = 'Hello';
189 | // console.log(message.charAt(0)); // Output: H
190 | // console.log(message.charCodeAt(0)); // Output: 72
191 |
192 |
193 | // String Split:
194 | // The split() method splits a string into an array of substrings based on a specified delimiter.
195 |
196 | // const message = 'Hello, World!';
197 | // console.log(message.split(',')); // Output: ["Hello", " World!"]
198 |
199 | // Method
200 | // String length
201 | // String slice()
202 | // String substring()
203 | // String substr()
204 | // String replace()
205 | // String replaceAll()
206 | // String toUpperCase()
207 | // String toLowerCase()
208 | // String concat()
209 | // String trim()
210 | // String trimStart()
211 | // String trimEnd()
212 | // String padStart()
213 | // String padEnd()
214 | // String charAt()
215 | // String charCodeAt()
216 | // String split()
217 |
218 | ```
--------------------------------------------------------------------------------
/Ch-4-String/index.js:
--------------------------------------------------------------------------------
1 | // Strings
2 |
3 | // 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.
4 |
5 | // Strings are used to store and manipulate text
6 |
7 | // String -> Collection of characters
8 |
9 | // Single Quotes -> let name = 'dp';
10 | // Double Quotes -> let name = "dp";
11 |
12 | let name = "dp";
13 | // console.log(name[3]); -> undefined
14 |
15 | // Template Literals
16 |
17 | // After ES6, Template Literals came into use, utilizing backticks (`).
18 |
19 | let boy1 = "hmm";
20 | let boy2 = 'ok';
21 |
22 | // Print "hmm nice ok"
23 | // let sentence = `boy1 "nice" 'is' boy2` -> We make a string using single or double quotes, both usage possible if string is made through backticks
24 |
25 | // String Interpolation
26 | let sentence = `${boy1} nice ${boy2}`;
27 | console.log(sentence); // Output: hmm nice ok
28 |
29 | let fruit = `Bana\'na`; // Bana'na
30 | console.log(fruit);
31 |
32 | // \' -> Escape character -> Count as one character
33 | // \n -> New line
34 | // \t -> Tab
35 | // \r -> Carriage return
36 |
37 | // String Methods & Properties
38 |
39 | // Accessing Characters:
40 | // Individual characters in a string can be accessed using square brackets and their index. Remember, indexing starts at 0.
41 |
42 | const message = 'Hello';
43 | console.log(message[0]); // Output: H
44 | console.log(message[3]); // Output: l
45 |
46 | // String Concatenation:
47 | // Strings can be concatenated using the + operator or the concat() method.
48 |
49 | const firstName = 'John';
50 | const lastName = 'Doe';
51 | const fullName = firstName + ' ' + lastName;
52 | console.log(fullName); // Output: John Doe
53 |
54 | // Using concat()
55 | const greetingMessage = 'Hello, ';
56 | const nameConcat = 'John';
57 | const greeting = greetingMessage.concat(nameConcat);
58 | console.log(greeting); // Output: Hello, John
59 |
60 | // Finding Substrings:
61 | // 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.
62 |
63 | const welcomeMessage = 'Hello, world!';
64 | console.log(welcomeMessage.indexOf('world')); // Output: 7
65 | console.log(welcomeMessage.indexOf('open')); // Output: -1
66 |
67 | // Extracting Substrings:
68 | // The slice() method extracts a portion of a string based on the start and end indexes.
69 |
70 | console.log(welcomeMessage.slice(0, 5)); // Output: Hello
71 | console.log(welcomeMessage.slice(7)); // Output: world!
72 |
73 | // Replacing Substrings:
74 | // The replace() method replaces a specified substring with another substring.
75 |
76 | const personalizedMessage = 'Hello, John!';
77 | console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice!
78 |
79 | // Splitting Strings:
80 | // The split() method splits a string into an array of substrings based on a specified delimiter.
81 |
82 | console.log(welcomeMessage.split(' ')); // Output: ["Hello,", "world!"]
83 |
84 | // Checking if a String Contains a Substring:
85 | // The includes() method checks if a string contains a specified substring and returns true or false.
86 |
87 | console.log(welcomeMessage.includes('World')); // Output: true
88 | console.log(welcomeMessage.includes('open')); // Output: false
89 |
90 | // String Length:
91 | // The length property returns the number of characters in a string.
92 |
93 | console.log(welcomeMessage.length); // Output: 13
94 |
95 | // String Slice:
96 | // The slice() method extracts a portion of a string based on the start and end indexes. It returns a new string.
97 |
98 | console.log(welcomeMessage.slice(7)); // Output: world!
99 | console.log(welcomeMessage.slice(0, 5)); // Output: Hello
100 |
101 | // String Substring:
102 | // The substring() method is similar to slice(), but it doesn't accept negative indexes. It returns a new string.
103 |
104 | console.log(welcomeMessage.substring(7)); // Output: world!
105 | console.log(welcomeMessage.substring(0, 5)); // Output: Hello
106 |
107 | // String Substr:
108 | // The substr() method extracts a portion of a string based on the start index and length. It returns a new string.
109 |
110 | console.log(welcomeMessage.substr(7)); // Output: world!
111 | console.log(welcomeMessage.substr(0, 5)); // Output: Hello
112 |
113 | // String Replace:
114 | // The replace() method replaces a specified substring with another substring. It returns a new string.
115 |
116 | console.log(personalizedMessage.replace('John', 'Alice')); // Output: Hello, Alice!
117 |
118 | // String ReplaceAll:
119 | // The replaceAll() method replaces all occurrences of a specified substring with another substring. It returns a new string. (Available from ECMAScript 2021)
120 |
121 | const repetitiveMessage = 'Hello, John! John is a good guy.';
122 | console.log(repetitiveMessage.replaceAll('John', 'Alice')); // Output: Hello, Alice! Alice is a good guy.
123 |
124 | // String toUpperCase and toLowerCase:
125 | // The toUpperCase() and toLowerCase() methods convert a string to uppercase and lowercase, respectively. They return a new string.
126 |
127 | console.log(welcomeMessage.toUpperCase()); // Output: HELLO, WORLD!
128 | console.log(welcomeMessage.toLowerCase()); // Output: hello, world!
129 |
130 | // String Concatenation:
131 | // The concat() method concatenates two or more strings and returns a new string.
132 |
133 | console.log(firstName.concat(' ', lastName)); // Output: John Doe
134 |
135 | // String Trim:
136 | // The trim() method removes whitespace from both ends of a string and returns a new string.
137 |
138 | const messageWithWhitespace = ' Hello, world! ';
139 | console.log(messageWithWhitespace.trim()); // Output: Hello, world!
140 |
141 | // String TrimStart and TrimEnd:
142 | // 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)
143 |
144 | console.log(messageWithWhitespace.trimStart()); // Output: Hello, world!
145 | console.log(messageWithWhitespace.trimEnd()); // Output: Hello, world!
146 |
147 | // String PadStart and PadEnd:
148 | // 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)
149 |
150 | const paddedMessage = 'Hello';
151 | console.log(paddedMessage.padStart(10, '*')); // Output: *****Hello
152 | console.log(paddedMessage.padEnd(10, '-')); // Output: Hello-----
153 |
154 | // String CharAt and CharCodeAt:
155 | // The charAt() method returns the character at a specified index in a string.
156 | // The charCodeAt() method returns the Unicode value of the character at a specified index in a string.
157 |
158 | console.log(message.charAt(0)); // Output: H
159 | console.log(message.charCodeAt(0)); // Output: 72
160 |
161 | // String Split:
162 | // The split() method splits a string into an array of substrings based on a specified delimiter.
163 |
164 | console.log(welcomeMessage.split(',')); // Output: ["Hello", " World!"]
165 |
166 | // Method summary:
167 | // String length
168 | // String slice()
169 | // String substring()
170 | // String substr()
171 | // String replace()
172 | // String replaceAll()
173 | // String toUpperCase()
174 | // String toLowerCase()
175 | // String concat()
176 | // String trim()
177 | // String trimStart()
178 | // String trimEnd()
179 | // String padStart()
180 | // String padEnd()
181 | // String charAt()
182 | // String charCodeAt()
183 | // String split()
--------------------------------------------------------------------------------
/Ch-6-JS-In-Browser.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-6-JS-In-Browser.zip
--------------------------------------------------------------------------------
/Ch-6-JS-In-Browser/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-6-JS-In-Browser/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | replit
8 |
9 |
10 |
11 |
12 | Hello world
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ch-6-JS-In-Browser/script.js:
--------------------------------------------------------------------------------
1 | // Element Tab -> All Element
2 | // Onsole Tab -> All The Error Plus Logs
3 | // Network Tab -> All The Network Request And Requirement
4 |
5 | // External File For Js -> File Cache Ho Jati he So Website Fast WOrk Karti He
6 | // We Can Add Js In Script Tag Also
7 | //
8 | //
9 |
10 | // Separation Of Concern and Cashing
11 |
12 | // Js Console Object
13 | // console.log(console)
14 | // console.error(error)
15 | // console.assert(assert)
16 | // console.clear()
17 | // console.table(table)
18 | // console.warn(warn)
19 | // console.info(info)
20 | // console.time(time)
21 | // console.timeEnd(timeEnd)
22 |
23 | // List All Method
24 | // console.log(console)
25 |
26 | // Output And Return Type Is There
27 | // console.log("Hey Darshan")
28 | // Output :
29 | // Hey Darshan
30 | // Undefined
31 |
32 | // Alert Prompt And Confirm
33 | // Alert -> Alert Box Show Karta Hai
34 | // Prompt -> Prompt Box Show Karta Hai -> Input Lene Ke Liye
35 | // Confirm -> Confirm Box Show Karta Hai -> Yes Or No Lene Ke Liye
36 |
37 | // alert("Enter The Value Of A")
38 | // let a = prompt("Enter A Here: ")
39 | // let a = prompt("Enter A Here: ", "578") // Default Value
40 | // document.write(a)
41 |
42 |
43 | // Confirm -> Yes Or No Lene Ke Liye
44 | // let write = confirm("Do You Want To Write It To The Page")
45 | // if (write) {
46 | // document.write(a)
47 | // } else {
48 | // document.write("Please Allow Me To Write")
49 | // }
50 |
51 | // 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
52 |
53 | // BOM And DOM
54 |
55 | // BOM -> Browser Object Model
56 | // DOM -> Document Object Model
57 | console.log(window)
58 | // window.console.log(window) -> Same Work Above
59 |
60 | // window is global object under that -> Bom , Dom , Js Core Feture Lies
61 |
62 | // Apke Pure HTML Page ko Document Represent Karta Hai -> Pure Page Ka Object Banke Usko Document Name De Diya Gaya He
63 | console.log(document)
64 | document.body.style.background = "yellow"
65 |
66 |
67 |
68 | // BOM (Browser Object Model):
69 | // 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.
70 |
71 |
72 | // Location href = "https://dpvasani56.com" -> Redirect To Another URL
73 |
74 | // console.log(window) => All Method
75 | // Window Object -> Global Object
76 |
--------------------------------------------------------------------------------
/Ch-6-JS-In-Browser/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | /* background: red; */
5 | }
--------------------------------------------------------------------------------
/Ch-7-Js-DOM.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-7-Js-DOM.zip
--------------------------------------------------------------------------------
/Ch-7-Js-DOM/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-7-Js-DOM/Readme.md:
--------------------------------------------------------------------------------
1 | 
--------------------------------------------------------------------------------
/Ch-7-Js-DOM/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-7-Js-DOM/image.png
--------------------------------------------------------------------------------
/Ch-7-Js-DOM/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | replit
8 |
9 |
10 |
11 |
12 |
13 |
14 | Home
15 | About
16 | Project
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Ch-7-Js-DOM/script.js:
--------------------------------------------------------------------------------
1 | // HTML Ko Convert Kar Diya He Js Object Me -> All Node Are Object
2 | // Text Node
3 | // Element Node
4 | // Comment Node
5 |
6 | // Auto Correction In HTML -> If Any Error In HTML Then It Will Be Auto Corrected
7 |
8 | // Walking The DOM
9 |
10 | // DOM Tree Traversal
11 | // document.body -> Page Body Tag
12 | // document.documentElement -> HTML Tag -> Page
13 | // document.head -> Head Tag
14 | // document.title -> String
15 |
16 | // document.body can be Null If The JavaScript Is Written Before The Body Tag
17 | // Children Of An Element -> Direct As Well As Deeply Nested Elements Of An Element Are Called Its Children
18 |
19 | // Child Nodes: Elements That Are Direct Children For Example Head And Body Are Children Of
20 |
21 | // Descendant Nodes: All Necessary Nodes Are Called Descendant Nodes For Example Head, Body, Title, Meta, Etc. Are Descendant Nodes Of
22 |
23 | // All Nested Elements , CHildren , Their Children And So On Are Called Their Siblings
24 |
25 | // First Child -> First Element Child -> element.firstChild
26 | // Last Child -> Last Element Child -> element.lastChild
27 | // Child Nodes (Element.childNodes) -> All Children
28 |
29 | // Following Are Always True
30 | // element.firstChild === element.childNodes[0]
31 | // element.lastChild === element.childNodes[element.childNodes.length - 1]
32 |
33 | // There Is Also A Method Element.hasChildNodes() To Check Whether There Are Any Child Nodes (Element.childNodes) Or Not
34 |
35 | // Child Nodes Are Not An Array But Can Be Converted Into Array -> Array.from(collection)
36 |
37 | // 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
38 |
39 | // Notes On Dom Collection
40 | // They Are Read Only
41 | // They Are Live Element.childNodes Variable (Reference) Will Be Updated Automatically If Child Nodes Of The Element Is Changed
42 | // They Are Iterable Using For...Of Loop
43 |
44 | // Siblings And Their Parents
45 |
46 | // Siblings Are Nodes That Are Children Of The Same Parent
47 | // For Example And Are Siblings. Siblings Have Same Parent In This Case
48 | // Is Said To Be The "Next" Or "Right" Sibling Of , Is Said To Be The "Previous" Or "Left" Sibling Of
49 | // The Next Sibling Is In NextSibling Property , And The Previous One Is In previousSibling Property
50 | // The Parent Is In parentNode Property
51 | // alert(document.documentElement.parentNode) -> Document
52 | // alert(document.documentElement.parentElement) -> Null
53 | // parentElement -> Ak Element Hai To Hi Return Hoga Verna Null Return Hoga
54 |
55 | // console.log(document.body.firstChild)
56 | // a = document.body.firstChild
57 | // console.log(a.parentNode)
58 | // console.log(a.parentElement)
59 | // console.log(a.firstChild.nextSibling)
60 |
61 |
62 |
63 | // Element Only Navigation
64 |
65 | // 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
66 |
67 |
68 | // let b = document.body
69 | // 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
70 | // console.log("First Element Child Of b Is : ", b.firstElementChild)
71 | // Only Element Type Ka First Child Dekhne Ko Milta He
72 |
73 | // const changeBgRed =()=>{
74 | // document.body.firstElementChild.style.background = "red"
75 |
76 | // }
77 |
78 | // document.previousElementSibling -> Previous Sibling Which Is An Element
79 | // document.nextElementSibling -> Next Sibling Which Is An Element
80 | // document.firstElementChild -> First Element Child
81 | // document.lastElementChild -> Last Element Child
82 |
83 | // Table Links
84 | // Certain DOM Elements May Provide Additional Properties Specific To Their Type For Example Table Elements Support -> table.rows -> Collection Of Tr Elements
85 |
86 | // table.rows -> Collection Of Tr Elements
87 | // table.caption -> Reference To
88 | // table.tHead -> Reference To
89 | // table.tFoot -> Reference To
90 | // table.tBodies -> Collection Of Elements
91 | // tbody.rows -> Collection Of Inside
92 | // tr.cells -> Collection Of Td And Th
93 | // tr.sectionRowIndex -> Index Of Tr In It's Section
94 | // tr.rowIndex -> Row Number Starting From 0
95 | // td.cellIndex -> No Of Cells In Row
96 |
97 |
98 | // Searching The DOM
99 | // document.getElementById() -> To Search Element By Id
100 | // document.querySelectorAll(.card-title) -> To Search Multiple Elements With Same CSS Selector
101 | // document.querySelector() -> To Search Single Element With CSS Selector
102 | // document.getElementsByTagName() -> To Search Element By Tag Name
103 | // document.getElementsByClassName() -> To Search Element By Class Name
104 | // document.getElementsByName() -> To Search Element By Name Attribute
105 |
106 | // let ctitle = document.getElementsByClassName("card-title")[0]
107 | // console.log(document.quarySelector(".card-title").getElemetByClassName("card-title"))
108 |
109 | // No S -> Return One Element
110 | // S -> Return All Elements -> Elements
111 |
112 | // Matches, Closest & Contains Methods
113 | // elem.matches(CSS) -> To Check If Element Matches The Given CSS Selector
114 | // elem.closest(CSS) -> To Look For The Nearest ancestor That Matches The Given CSS Selector.
115 | // No Than Go to Perent Hai TO Return So And So
116 |
117 | // let id1 = document.getElementById("id1")
118 | // let sp1 = document.getElementById("sp1")
119 | // console.log(id1.matches(".class"))
120 |
121 | // elem.contains(elem) -> Returns True If Element B Is Inside Element A (A Descendant Of B) Or When Element A == Element B
122 |
123 |
124 | // Chapter 7 Practice Set
125 | // Q1 -> Create A Navbar And Change The Color Of Its First Element To Red
126 | // document.getElementsByTagName("nav")[0].firstElementChild.style.color = "red"
127 | // Q2 -> Create A Table Using JavaScript Which Background Color To Green
128 | // document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
129 | // Q3 -> Create An Element With 3 Children. Now Change The Color Of First And Last Element To Green
130 | // document.getElementsByTagName("nav")[0].firstElementChild.style.color = "green"
131 | // document.getElementsByTagName("nav")[0].lastElementChild.style.color = "green"
132 | // Q4 -> Write A JavaScript Code To Change Background Of All Tags To Cyan
133 | // Array.from(document.getElementsByTagName("li")).forEach((element) => {
134 | // element.style.background = "cyan";
135 | // })
136 | // Q5 -> Which Of The Following Is Used To Look For The Farthest Ancestor That Matches A Given CSS Selector
137 | // (a) matches (b) closest (c) contains (d) none of these
138 | // Ans -> None Of These
139 |
--------------------------------------------------------------------------------
/Ch-7-Js-DOM/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | }
--------------------------------------------------------------------------------
/Ch-8-Events-And-Other-DOM-Properties.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-8-Events-And-Other-DOM-Properties.zip
--------------------------------------------------------------------------------
/Ch-8-Events-And-Other-DOM-Properties/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-8-Events-And-Other-DOM-Properties/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | InnerHTML
8 |
9 |
10 |
11 |
12 |
13 | Hey I Am Container
14 |
Hey I AM Good
15 |
16 |
Click Me
17 |
18 |
Chow
19 | Vadapow
20 | Paubhaji
21 |
22 |
23 |
24 |
Bookmarks
25 |
Google
26 |
Facebook
27 |
28 |
Instagram
29 |
30 |
31 |
32 | Hello world
33 | Hi Bold Tag Hey I Am Span
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/Ch-8-Events-And-Other-DOM-Properties/script.js:
--------------------------------------------------------------------------------
1 | // console.log(document.getElementsByTagName('span')[0])
2 | // console.dir(document.getElementsByTagName('span')[0]) // -> Span Ko Object Dikhayega With Its Properties
3 |
4 | // console.log -> Shows the element DOM tree
5 | // console.dir -> Shows the element as an object with its properties
6 |
7 | // console.log(document.body.firstChild.nodeName)
8 | // console.log(document.body.firstElementChild.nodeName)
9 |
10 | // TagName/ NodeName
11 | // TagName -> Only Exists For Element Nodes
12 | // NodeName -> Defined For Any Node (Text, Comment, etc)
13 |
14 | // innerHTML / outerHTML
15 | // innerHTML -> The Inner HTML Property allows to get the HTML inside the element as a string. -> Work For Element Nodes Only
16 |
17 | // outerHTML -> The outerHTML property contains the full HTML. -> Work For All Nodes
18 |
19 | // outerHTML Property Contain The Full HTML innerHTML + The Element Itself
20 | // first.innerHtml -> Help In Get Or Set The Inner HTML
21 | // first.innerHtml = "Hey I Am Italic " -> Insertion
22 |
23 | // first.outerHTML -> Help In Get Or Set The Outer HTML
24 | // Output -> Hey I Am Italic
25 |
26 |
27 | // document.body.firstChild.data -> Gives The Data Of The First Child
28 | // document.body.firstChild.nodeValue -> Same As Data
29 |
30 | // Text Content
31 | // The textContent property allows to get the text inside the element as a string. Only Works For Element Nodes
32 |
33 | // console.log(document.body.textContent)
34 |
35 | // Hidden Property
36 | // The hidden attribute and the DOM property specifies whether the element is visible or not.
37 | // first.hidden = false -> Shows The Element
38 | // first.hidden = true -> Hides The Element
39 |
40 | // Attributes Method
41 | // 1. elem.hasAttribute(name) -> Method To Check For Existence Of An Attribute
42 | // 2. elem.getAttribute(name) -> Method Used To Get The Value Of An Attribute
43 | // 3. elem.setAttribute(name, value) -> Method Used To Set The Value Of An Attribute
44 | // 4. elem.removeAttribute(name) -> Method Used To Remove The Attribute From Element
45 | // 5. elem.attributes -> Method To Get The Collection Of All Attributes
46 | // Data-* Attributes
47 | // 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
48 | // If An Element Has An Attribute Named "data-one" -> The Way To Access This Attribute Is : elem.dataset.one
49 |
50 |
51 | // let a = first.getAttribute("class")
52 | // console.log(a)
53 |
54 |
55 | // console.log(first.hasAttribute("class"))
56 | // console.log(first.hasAttribute("style"))
57 | // // first.setAttribute("hidden", "true")
58 | // first.setAttribute("class", "true sachin")
59 | // first.removeAttribute("class")
60 | // console.log(first.attributes)
61 | // console.log(first.dataset)
62 | // console.log(first.dataset.game)
63 | // console.log(first.dataset.player)
64 |
65 |
66 | // Always Add Custom Attribute With Data-_____
67 | // Data Attributes
68 | // data-one = "one" -> data-one -> One
69 | // data-game = "mario" -> data-game -> Mario
70 |
71 | // If Element Has A Attribute Named "data-one" -> The Way To Access This Attribute Is : elem.dataset.one
72 |
73 | // Insertion Method
74 |
75 | // There Are Three Way To Insert HTML Into The DOM
76 |
77 | // 1. innerHTML
78 |
79 | // let a = document.getElementsByTagName('div')[0]
80 | // a.innerHTML = a.innerHTML + 'Hello World! ';
81 |
82 |
83 | // 2. document.createElement()
84 | // let div = document.createElement('div');
85 | // div.innerHTML = 'Hello World! ';
86 | // a.appendChild(div);
87 | // div.className = "alert"
88 | // We Can Use For Loop In This Case
89 |
90 | // 3. document.createTextNode()
91 | // let div = document.createTextNode('This Is Text Node');
92 | // a.appendChild(div);
93 |
94 | // Node Insertion Method
95 | // 4. node.append(e) -> Append At The End Of Node
96 |
97 | // 5. node.prepend() -> Insert At The Beginning Of Node
98 |
99 | // 6. node.before() -> Insert Before Node
100 |
101 | // 7. node.after() -> Insert After Node
102 |
103 | // 8. node.replaceWith() -> Replace Node With Another Node
104 |
105 | // Insert Adjacent HTML / Text / Element
106 |
107 | // first.insertAdjacentHTML('beforebegin', 'beforebegin
');
108 | // first.insertAdjacentHTML('beforeend', 'beforeend
');
109 | // first.insertAdjacentHTML('afterbegin', 'afterbegin
');
110 | // first.insertAdjacentHTML('afterend', 'afterend
');
111 |
112 | // Node Removal
113 | // first.remove() -> Remove The Element
114 |
115 |
116 | // ClassName & ClassList
117 | // className -> Used To Add/Remove/Toggle A Class
118 | // classList -> Used To Add/Remove/Toggle A Class
119 | // first.className = "text-black red"
120 | // first.classList.remove("red") // Remove Karva
121 | // first.classList.add("red") // Add Karva
122 | // first.classList.toggle("red") // He To Hata Dega Nahi He to Laga Dega
123 | // first.classList.contains("red") // Check If Contain Or Not? -> True False
124 |
125 | // SetTimeout And SetInterval
126 |
127 | // setTimeout(function, , , )
128 | // setTimeOut -> Kuch Time Ke Bad Apni JS Ko execute Karna Hoga -> Execute The Js After Certain Time
129 | // clearTimeout -> To Clear The SetTimeout
130 | // setInterval -> In Certain Interval Of Time Hame Bar Bar Apni Js Ko Execute Karna Hoga -> Execute The Js After Certain Time(Interval)
131 | // setTimeout -> Is Function Ko Run Kardo Itne Time Ke Bad
132 |
133 | // alert("Hello")
134 | // let a = setTimeout(function() {
135 | // alert("I Am Inside Of SetTimeout")
136 | // }, 2000)
137 | // clearTimeout(a)
138 | // console.log(a) // Timer Id
139 |
140 | // let timerId = setInterval(function, , , )
141 | // Delay In millisecond
142 | // Timer Id Return Me Milti He
143 |
144 | // const sum = (a, b, c) => (){
145 | // console.log("Yes I Am Running " + (a + b + c))
146 | // a + b
147 | // }
148 |
149 | // setTimeout(sum, 1000, 1, 2, 7)
150 | // clearTimeout(timerId)
151 |
152 | // setInterval -> Bar Bar Kuch Time Ke Bad Run Karna
153 | // Syntex -> setInterval(function, , , )
154 |
155 | // Example:
156 | // let a = setInterval(function() {
157 | // console.log("I Am In SetInterval")
158 | // }, 3000)
159 |
160 |
161 | // clearInterval(a) -> To Clear The SetInterval
162 |
163 | // Browser Events
164 |
165 | // An Event Is A Signal That Something Has Happened.
166 | // All Dom Node Generate Such Signal
167 |
168 | // Mouse Events -> click, contextmenu, mouseover/mouseout, mousedown/mouseup, mousemove
169 |
170 | // Keyboard Events -> keydown and keyup
171 | // Form Element Events -> submit, focus
172 | // Document Events -> DOMContentLoaded
173 |
174 | // Click Me
175 |
176 | // Handling Events
177 | // elem.onclick = function(e){
178 | // alert("Hello World1!")
179 | // }
180 |
181 | // let a = document.getElementsByClassName("container")[0]
182 | // console.log(a)
183 | // a.onclick = () => {
184 | // let b = document.getElementsByClassName("container")[0]
185 | // b.innerHTML = "Hello World!"
186 | // }
187 |
188 | // If Onclick Js and HTML Me Likha Hai To Js Vala Priorty Hota Hai
189 |
190 | // Adding A Handler With JavaScript Overwrite The Existing Handler
191 |
192 | // Event Listener
193 |
194 | // addEventListener(event, handler) and removeEventListener(event, handler)
195 |
196 | // Handler Must Be Same While Removing It
197 |
198 | // addeventListener -> To Assign Multiple Handlers To An Event
199 |
200 | // let x = function(e) {
201 | // alert("Hello World1!")
202 | // }
203 | // let y = function(e) {
204 | // console.log(e) // Event Object -> Pointing To The Our Function
205 | // // console.log(e.target)
206 | // alert("Hello World2!")
207 | // }
208 | // btn.addEventListener('click', x)
209 |
210 | // btn.addEventListener('click', function(e) {
211 | // alert("Hello World2!")
212 | // })
213 |
214 | // btn.addEventListener('click', y)
215 |
216 | // let a = prompt("What is Your Favourite Number?");
217 | // if (a == "2") {
218 | // btn.removeEventListener('click', x)
219 | // }
220 |
221 | // For This Work Function OBject Same Hona Cahiye -> Means That We Want to Remove Function y that We Must Pass The Function y So That Function Object Can Removed
222 |
223 |
224 | // Event Object
225 |
226 | // 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
227 |
228 | // elem.onclick = function(event){
229 | // Code
230 | // }
231 |
232 | // event.type -> Event Type
233 | // event.currentTarget -> Element That Handled The Event
234 | // event.clientX/ event.clientY -> Coordinates Of Cursor
235 |
236 |
237 | // Practice Set
238 |
239 | // Q1 -> Create A Website Which Stores Bookmarks Of Your Favourite Website Using href
240 | // Ans: Ans On HTML File
241 | // Q2 -> Write A Program To Show Different Alerts When Different Buttons Are Clicked
242 | // Ans: Ans On HTML File
243 | // Q3 -> Create A Website Which Stores Bookmarks Of Your Favourite Website Using Event Listeners
244 | // document.getElementById("google").addEventListener("click", function() {
245 | // window.location = "https://www.google.com";
246 | // win.focus();
247 | // })
248 | // document.getElementById("fb").addEventListener("click", function() {
249 | // window.location = "https://www.facebook.com";
250 | // win.focus();
251 | // })
252 | // document.getElementById("twitter").addEventListener("click", function() {
253 | // window.location = "https://www.twitter.com";
254 | // win.focus();
255 | // })
256 | // document.getElementById("insta").addEventListener("click", function() {
257 | // window.location = "https://www.instagram.com";
258 | // win.focus();
259 | // })
260 |
261 |
262 | // Q4 -> Write A JavaScript Program To Keep fetcing contents of a website (Every 5 Seconds)
263 |
264 | // setInterval(async function() {
265 | // let url = "https://jsonplaceholder.typicode.com/todos/1"
266 | // console.log(await fetchContent(url))
267 | // },3000)
268 |
269 | // const fetchContent = async (url) =>{
270 | // con = await fetch(url);
271 | // let a = await con.json()
272 | // return a;
273 | // }
274 |
275 | // Q5 -> Create A Glowing Bulb Effect Using ClassList Toggle Method In JavaScript
276 |
277 |
278 | // setInterval(async function(){
279 | // document.querySelector("#bulb").classList.toggle("bulb")
280 | // },300)
281 |
282 | // Clock
283 |
284 | // let a = new Date()
285 | // let h = a.getHours()
286 | // let m = a.getMinutes()
287 | // let s = a.getSeconds()
288 |
289 |
--------------------------------------------------------------------------------
/Ch-8-Events-And-Other-DOM-Properties/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | }
5 |
6 | .yellow {
7 | background-color: yellow;
8 | color: white;
9 | }
10 |
11 | .red {
12 | background-color: red;
13 | color: white;
14 | }
15 |
16 | .text-dark {
17 | color: black;
18 | }
19 |
20 | .bulb{
21 | height : 341px;
22 | width : 341px;
23 | background:yellow;
24 | }
25 | .bulbcontainer{
26 | height : 341px;
27 | width : 341px;
28 | }
--------------------------------------------------------------------------------
/Ch-9-Callbacks-Promises-And-AsyncAwait.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-9-Callbacks-Promises-And-AsyncAwait.zip
--------------------------------------------------------------------------------
/Ch-9-Callbacks-Promises-And-AsyncAwait/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/Ch-9-Callbacks-Promises-And-AsyncAwait/Readme.md:
--------------------------------------------------------------------------------
1 | ### Callback Functions and Error Handling in JavaScript
2 |
3 | **Callback Functions**
4 |
5 | In JavaScript, functions can be passed as arguments to other functions. These functions are called **callback functions**. A callback function is executed after the main function has finished executing. This is a common way to handle asynchronous operations.
6 |
7 | **Example: Callback Function**
8 |
9 | ```javascript
10 | function fetchData(callback) {
11 | setTimeout(() => {
12 | const data = { name: 'John', age: 30 };
13 | callback(data);
14 | }, 2000);
15 | }
16 |
17 | function displayData(data) {
18 | console.log(`Name: ${data.name}, Age: ${data.age}`);
19 | }
20 |
21 | fetchData(displayData);
22 | ```
23 |
24 | In this example, `fetchData` simulates an asynchronous operation using `setTimeout`. Once the data is fetched, the `callback` function `displayData` is called with the fetched data.
25 |
26 | **Error Handling with Callbacks**
27 |
28 | When dealing with asynchronous operations, it is crucial to handle errors effectively. The convention in JavaScript is to pass an error object as the first argument to the callback function.
29 |
30 | **Example: Error Handling with Callbacks**
31 |
32 | ```javascript
33 | function fetchData(callback) {
34 | setTimeout(() => {
35 | const error = false; // Change to true to simulate an error
36 | const data = { name: 'John', age: 30 };
37 |
38 | if (error) {
39 | callback('Error: Unable to fetch data', null);
40 | } else {
41 | callback(null, data);
42 | }
43 | }, 2000);
44 | }
45 |
46 | function handleResponse(error, data) {
47 | if (error) {
48 | console.error(error);
49 | } else {
50 | console.log(`Name: ${data.name}, Age: ${data.age}`);
51 | }
52 | }
53 |
54 | fetchData(handleResponse);
55 | ```
56 |
57 | In this example, the `fetchData` function simulates an asynchronous operation that might fail. If an error occurs, the callback is called with an error message; otherwise, it is called with the data.
58 |
59 | **Best Practices for Callbacks and Error Handling**
60 |
61 | 1. **Always Handle Errors**: Ensure that every callback function is capable of handling errors gracefully.
62 | 2. **Avoid Callback Hell**: Refactor deeply nested callbacks using Promises or async/await.
63 | 3. **Clear and Descriptive Error Messages**: Provide meaningful error messages to help with debugging.
64 |
65 | **Example: Refactoring with Promises**
66 |
67 | To avoid the complexities of nested callbacks, you can use Promises, which provide a more elegant way to handle asynchronous operations and errors.
68 |
69 | ```javascript
70 | function fetchData() {
71 | return new Promise((resolve, reject) => {
72 | setTimeout(() => {
73 | const error = false; // Change to true to simulate an error
74 | const data = { name: 'John', age: 30 };
75 |
76 | if (error) {
77 | reject('Error: Unable to fetch data');
78 | } else {
79 | resolve(data);
80 | }
81 | }, 2000);
82 | });
83 | }
84 |
85 | fetchData()
86 | .then(data => {
87 | console.log(`Name: ${data.name}, Age: ${data.age}`);
88 | })
89 | .catch(error => {
90 | console.error(error);
91 | });
92 | ```
93 |
94 | In this example, `fetchData` returns a Promise. If the operation is successful, the Promise is resolved with the data. If an error occurs, the Promise is rejected with an error message. The `then` method handles the resolved data, and the `catch` method handles the error.
95 |
96 | By using Promises, you can avoid callback hell and write cleaner, more readable code.
97 |
98 | **Conclusion**
99 |
100 | Callback functions are essential in JavaScript for handling asynchronous operations. Proper error handling in callbacks is crucial for building robust applications. Promises provide a more manageable alternative to callbacks, allowing you to write cleaner and more maintainable asynchronous code.
101 |
102 | ---
103 |
104 | This section provides an overview of callback functions and error handling in JavaScript, along with best practices and examples for writing and refactoring asynchronous code.
105 |
106 |
107 | 
108 |
109 |
110 | The `loadScript` function you've provided is a nice example of how to load external scripts asynchronously using Promises in JavaScript. The function returns a Promise that resolves when the script is successfully loaded and rejects if there's an error during the loading process.
111 |
112 | Here's the complete code including a continuation after the `p1.then` block:
113 |
114 | ```javascript
115 | const loadScript = (src) => {
116 | return new Promise((resolve, reject) => {
117 | let script = document.createElement("script");
118 | script.type = "text/javascript";
119 | script.src = src;
120 | document.body.appendChild(script);
121 |
122 | script.onload = () => {
123 | resolve("Script has been loaded successfully");
124 | };
125 |
126 | script.onerror = () => {
127 | reject(new Error(`Failed to load script: ${src}`));
128 | };
129 | });
130 | };
131 |
132 | // Load the script and chain the promises
133 | let p1 = loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js");
134 |
135 | p1.then((value) => {
136 | console.log(value);
137 | // Loading another script after the first one is loaded
138 | return loadScript("https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js");
139 | })
140 | .then((value) => {
141 | console.log(value);
142 | // You can continue chaining more scripts if needed
143 | })
144 | .catch((error) => {
145 | console.error("Script loading failed:", error);
146 | });
147 | ```
148 |
149 | ### Explanation:
150 |
151 | 1. **loadScript Function**:
152 | - The `loadScript` function creates a new script element with the provided `src` URL and appends it to the document's body.
153 | - If the script loads successfully, the `onload` event triggers and resolves the Promise.
154 | - If the script fails to load, the `onerror` event triggers and rejects the Promise with an error.
155 |
156 | 2. **Chaining Promises**:
157 | - After the first script is loaded (`p1.then`), it returns another call to `loadScript`, loading the same script again.
158 | - You can chain as many `.then()` calls as needed to load multiple scripts sequentially.
159 |
160 | 3. **Error Handling**:
161 | - If any of the script loads fail, the `catch` block will handle the error, providing a descriptive message about what went wrong.
162 |
163 |
164 | ### 1. **Promise Chaining**:
165 | - **True**: When you chain Promises using `.then()`, each Promise in the chain runs sequentially, meaning the next `.then()` is executed only after the previous one resolves.
166 | - Example:
167 | ```javascript
168 | new Promise((resolve) => setTimeout(() => resolve("First"), 5000))
169 | .then((value) => {
170 | console.log(value);
171 | return new Promise((resolve) => setTimeout(() => resolve("Second"), 5000));
172 | })
173 | .then((value) => {
174 | console.log(value);
175 | });
176 | ```
177 | - If you have 10 chained Promises, each with a `setTimeout` of 5 seconds, the total execution time would be approximately 50 seconds (5 seconds for each).
178 |
179 | ### 2. **Attaching Multiple Handlers to a Promise**:
180 | - **True**: You can attach multiple `.then()` handlers to the same Promise. These handlers will run independently of each other.
181 | - Example:
182 | ```javascript
183 | let promise = new Promise((resolve) => setTimeout(() => resolve("Done"), 5000));
184 |
185 | promise.then((value) => {
186 | console.log("Handler 1: " + value);
187 | });
188 |
189 | promise.then((value) => {
190 | console.log("Handler 2: " + value);
191 | });
192 | ```
193 | - In this case, both handlers will run after the Promise resolves, and they'll run almost simultaneously. If you had 10 handlers attached to the same Promise, they would all execute after the initial 5-second delay, but they would not add any additional delay.
194 |
195 | ### **Summary**:
196 | - **Promise Chaining**: Executes one after the other. Multiple chained Promises with a `setTimeout` of 5 seconds each will take 50 seconds in total if there are 10 Promises.
197 | - **Multiple Handlers on the Same Promise**: These handlers run independently of each other. If you attach multiple handlers to a single Promise, and the Promise has a `setTimeout` of 5 seconds, all handlers will run in parallel after the 5 seconds, so the total time will be just 5 seconds.
198 |
199 |
200 | ### Static Methods of the `Promise` Class
201 |
202 | 1. **`Promise.all(promises)`**
203 | - **Explanation**: This method takes an array of Promises and waits for all of them to resolve. If all Promises resolve successfully, it returns an array of their results. If any one of the Promises rejects, `Promise.all` will immediately reject with that error, and all other results are ignored.
204 | - **Example**:
205 | ```javascript
206 | let promise1 = Promise.resolve(10);
207 | let promise2 = Promise.resolve(20);
208 | let promise3 = Promise.resolve(30);
209 |
210 | Promise.all([promise1, promise2, promise3])
211 | .then((results) => {
212 | console.log(results); // Output: [10, 20, 30]
213 | })
214 | .catch((error) => {
215 | console.error(error);
216 | });
217 | ```
218 |
219 | 2. **`Promise.allSettled(promises)`**
220 | - **Explanation**: This method waits for all Promises to settle (either resolved or rejected) and returns an array of objects. Each object has a `status` (either "fulfilled" or "rejected") and a `value` or `reason` depending on whether the Promise was fulfilled or rejected.
221 | - **Example**:
222 | ```javascript
223 | let promise1 = Promise.resolve(10);
224 | let promise2 = Promise.reject("Error occurred");
225 | let promise3 = Promise.resolve(30);
226 |
227 | Promise.allSettled([promise1, promise2, promise3])
228 | .then((results) => {
229 | console.log(results);
230 | // Output: [
231 | // { status: "fulfilled", value: 10 },
232 | // { status: "rejected", reason: "Error occurred" },
233 | // { status: "fulfilled", value: 30 }
234 | // ]
235 | });
236 | ```
237 |
238 | 3. **`Promise.race(promises)`**
239 | - **Explanation**: This method waits for the first Promise to settle (either resolve or reject). The result or error of that first settled Promise becomes the output.
240 | - **Example**:
241 | ```javascript
242 | let promise1 = new Promise((resolve) => setTimeout(() => resolve("First"), 100));
243 | let promise2 = new Promise((resolve) => setTimeout(() => resolve("Second"), 200));
244 |
245 | Promise.race([promise1, promise2])
246 | .then((result) => {
247 | console.log(result); // Output: "First"
248 | })
249 | .catch((error) => {
250 | console.error(error);
251 | });
252 | ```
253 |
254 | 4. **`Promise.any(promises)`**
255 | - **Explanation**: This method waits for the first Promise that resolves successfully. If no Promise resolves and all are rejected, it throws an `AggregateError` with all the rejection reasons.
256 | - **Example**:
257 | ```javascript
258 | let promise1 = Promise.reject("Error 1");
259 | let promise2 = new Promise((resolve) => setTimeout(() => resolve("Success"), 100));
260 | let promise3 = Promise.reject("Error 2");
261 |
262 | Promise.any([promise1, promise2, promise3])
263 | .then((result) => {
264 | console.log(result); // Output: "Success"
265 | })
266 | .catch((error) => {
267 | console.error(error.errors); // Output: ["Error 1", "Error 2"]
268 | });
269 | ```
270 |
271 | 5. **`Promise.resolve(value)`**
272 | - **Explanation**: This method creates a Promise that is immediately resolved with the provided value.
273 | - **Example**:
274 | ```javascript
275 | let promise = Promise.resolve("Immediate resolve");
276 |
277 | promise.then((result) => {
278 | console.log(result); // Output: "Immediate resolve"
279 | });
280 | ```
281 |
282 | 6. **`Promise.reject(error)`**
283 | - **Explanation**: This method creates a Promise that is immediately rejected with the provided error.
284 | - **Example**:
285 | ```javascript
286 | let promise = Promise.reject("Immediate reject");
287 |
288 | promise.catch((error) => {
289 | console.error(error); // Output: "Immediate reject"
290 | });
291 | ```
292 |
--------------------------------------------------------------------------------
/Ch-9-Callbacks-Promises-And-AsyncAwait/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dpvasani/JavaScript-Ultimate-Code/b347ae7ec03b527271cc8c3db3051867986fe8c7/Ch-9-Callbacks-Promises-And-AsyncAwait/image.png
--------------------------------------------------------------------------------
/Ch-9-Callbacks-Promises-And-AsyncAwait/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | replit
8 |
9 |
10 |
11 |
12 | Hello world
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ch-9-Callbacks-Promises-And-AsyncAwait/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | width: 100%;
4 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## 🌐 Socials:
4 |
5 |
6 | Connect with me :
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | [](https://github.com/dpvasani/JavaScript-Ultimate-Code)
21 |
22 | # JavaScript Ultimate Code
23 |
24 | ## Overview
25 |
26 | Welcome to the **JavaScript-Ultimate-Code** repository! This repository contains a comprehensive collection of JavaScript notes, code examples, and practice sets designed to help you master both fundamental and advanced JavaScript concepts. Each chapter includes practical exercises and code examples to reinforce your understanding.
27 |
28 | ## Table of Contents
29 |
30 | 1. [Chapter 1: Variables](#chapter-1-variables)
31 | 2. [Chapter 2: Expressions & Conditional Statements](#chapter-2-expressions--conditional-statements)
32 | 3. [Chapter 3: Loops & Functions](#chapter-3-loops--functions)
33 | 4. [Chapter 4: Strings](#chapter-4-strings)
34 | 5. [Chapter 5: Arrays](#chapter-5-arrays)
35 | 6. [Chapter 6: JavaScript in the Browser](#chapter-6-javascript-in-the-browser)
36 | 7. [Chapter 7: DOM Manipulation](#chapter-7-dom-manipulation)
37 | 8. [Chapter 8: Events & Other DOM Properties](#chapter-8-events--other-dom-properties)
38 | 9. [Chapter 9: Callbacks, Promises, and Async/Await](#chapter-9-callbacks-promises-and-asyncawait)
39 | 10. [Chapter 10: Network Requests and Storing Data](#chapter-10-network-requests-and-storing-data)
40 | 11. [Chapter 11: Object-Oriented Programming](#chapter-11-object-oriented-programming)
41 | 12. [Chapter 12: Advanced JavaScript](#chapter-12-advanced-javascript)
42 |
43 | ## Chapters
44 |
45 | | Chapter | Files |
46 | |---------|---------------------------------------------------------|
47 | | **Chapter 1: Variables** | [Ch 1 Variable.js](Ch%201%20Variable.js) [Ch 1 Practice Set.js](Ch%201%20Practice%20Set.js) |
48 | | **Chapter 2: Expressions & Conditional Statements**| [Ch 2 Expression & Conditional Statement.js](Ch%202%20Expression%20&%20Conditional%20Statement.js) [Ch 2 Expression & Conditional Statement Practice Set.js](Ch%202%20Expression%20&%20Conditional%20Statement%20Practice%20Set.js) |
49 | | **Chapter 3: Loops & Functions** | [Ch 3 Loops & Functions.js](Ch%203%20Loops%20&%20Functions.js) [Ch 3 Loops & Functions Practice Set.js](Ch%203%20Loops%20&%20Functions%20Practice%20Set.js) |
50 | | **Chapter 4: Strings** | [Ch 4 String.js](Ch%204%20String.js) [Ch 4 String Practice Set.js](Ch%204%20String%20Practice%20Set.js) |
51 | | **Chapter 5: Arrays** | [Ch 5 Array.js](Ch%205%20Array.js) [Ch 5 Array Practice Set.js](Ch%205%20Array%20Practice%20Set.js) |
52 | | **Chapter 6: JavaScript in the Browser** | [Ch 6 JavaScript In Browser.js](Ch%206%20JavaScript%20In%20Browser.js) [Ch 6 JavaScript In Browser Practice Set.js](Ch%206%20JavaScript%20In%20Browser%20Practice%20Set.js) |
53 | | **Chapter 7: DOM Manipulation** | [Ch 7 DOM Part 1.js](Ch%207%20DOM%20Part%201.js) [Ch 7 DOM Part 2.js](Ch%207%20DOM%20Part%202.js) [Ch 7 DOM Practice Set.js](Ch%207%20DOM%20Practice%20Set.js) [Ch 7 Js DOM.js](Ch%207%20Js%20DOM.js) |
54 | | **Chapter 8: Events & Other DOM Properties** | [Ch 8 Event & Other DOM Properties.js](Ch%208%20Event%20&%20Other%20DOM%20Properties.js) [Ch 8 Events And Other DOM Properties.js](Ch%208%20Events%20And%20Other%20DOM%20Properties.js) |
55 | | **Chapter 9: Callbacks, Promises, and Async/Await**| [Ch 9 Callbacks, Promises And Async And Await.js](Ch%209%20Callbacks,%20Promises%20And%20Async%20And%20Await.js) |
56 | | **Chapter 10: Network Requests and Storing Data** | [Ch 10 Network Request And Storing Data.js](Ch%2010%20Network%20Request%20And%20Storing%20Data.js) |
57 | | **Chapter 11: Object-Oriented Programming** | [Ch 11 Object Oriented Programing.js](Ch%2011%20Object%20Oriented%20Programing.js) |
58 | | **Chapter 12: Advanced JavaScript** | [Ch 12 Advanced JavaScript.js](Ch%2012%20Advanced%20JavaScript.js) |
59 |
60 | ## Getting Started
61 |
62 | To get started with this repository, clone it to your local machine:
63 |
64 | ```bash
65 | git clone https://github.com/dpvasani/JavaScript-Ultimate-Code.git
66 | ```
67 |
68 | ## Contributing
69 |
70 | Contributions are welcome! Please create a pull request with a detailed description of your changes.
71 |
72 | ## License
73 |
74 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
75 |
--------------------------------------------------------------------------------