├── .gitignore
├── Images
├── Class.png
├── Codingprocess.png
├── DOM_tree.png
├── How Js works.pdf
├── HowJsComplie.png
├── HowJsInterpret.png
├── HowJsJIT.png
└── JITimg.png
├── Readme.md
└── _config.yml
/.gitignore:
--------------------------------------------------------------------------------
1 | .prettierrc
--------------------------------------------------------------------------------
/Images/Class.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/Class.png
--------------------------------------------------------------------------------
/Images/Codingprocess.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/Codingprocess.png
--------------------------------------------------------------------------------
/Images/DOM_tree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/DOM_tree.png
--------------------------------------------------------------------------------
/Images/How Js works.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/How Js works.pdf
--------------------------------------------------------------------------------
/Images/HowJsComplie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/HowJsComplie.png
--------------------------------------------------------------------------------
/Images/HowJsInterpret.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/HowJsInterpret.png
--------------------------------------------------------------------------------
/Images/HowJsJIT.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/HowJsJIT.png
--------------------------------------------------------------------------------
/Images/JITimg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Chandraprakash-Darji/js-recap/bea9e31f3ee83842c3dece2abae5e9e4d16d68a3/Images/JITimg.png
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 | # Notes for Javascript
2 |
3 | **[Live Site Link](https://chandraprakash-darji.github.io/js-recap/)**
4 |
5 | _(Credits [Jonas Schmedtmann](https://twitter.com/jonasschmedtman) JS Course for amazing content that i learned)_
6 |
7 | **Navigate to the Topic**
8 |
9 | - [Notes for Javascript](#notes-for-javascript)
10 | - [Basis of JS](#basis-of-js)
11 | - [The 7 Primitive Data types](#the-7-primitive-data-types)
12 | - [Operators in JS](#operators-in-js)
13 | - [Arithmetic Operators](#arithmetic-operators)
14 | - [Assignment Operators](#assignment-operators)
15 | - [Comparison Operators](#comparison-operators)
16 | - [Logical Operators](#logical-operators)
17 | - [Ternary Operators](#ternary-operators)
18 | - [Spread/Rest Operator](#spreadrest-operator)
19 | - [Template literals (Template strings)](#template-literals-template-strings)
20 | - [Conditional Statment ( if-Else )](#conditional-statment--if-else-)
21 | - [Type Conversion and Coercion](#type-conversion-and-coercion)
22 | - [Type Conversion](#type-conversion)
23 | - [Falsy values](#falsy-values)
24 | - [Truely Value](#truely-value)
25 | - [Type Coercion](#type-coercion)
26 | - [Switch Statment](#switch-statment)
27 | - [Functions](#functions)
28 | - [Default Arguments](#default-arguments)
29 | - [How passing argument Works :: value vs. Refrence](#how-passing-argument-works--value-vs-refrence)
30 | - [First Class and Higher Order Function](#first-class-and-higher-order-function)
31 | - [Some Properties of First-Class Functions](#some-properties-of-first-class-functions)
32 | - [Higher Order Functions](#higher-order-functions)
33 | - [Some Properties of Higher-Order Functions](#some-properties-of-higher-order-functions)
34 | - [Function that recevies another function](#function-that-recevies-another-function)
35 | - [Function that returns a new function](#function-that-returns-a-new-function)
36 | - [Implimentation](#implimentation)
37 | - [Function Accepting CallBacks](#function-accepting-callbacks)
38 | - [Function Returninng the Function](#function-returninng-the-function)
39 | - [Call Method](#call-method)
40 | - [Apply Method](#apply-method)
41 | - [Bind Method](#bind-method)
42 | - [Imediately Invoked Functions](#imediately-invoked-functions)
43 | - [Arrays](#arrays)
44 | - [Objects](#objects)
45 | - [Sets](#sets)
46 | - [Maps](#maps)
47 | - [Working With String](#working-with-string)
48 | - [Data Strucutres](#data-strucutres)
49 | - [List of data Strucures](#list-of-data-strucures)
50 | - [Sources of Data](#sources-of-data)
51 | - [Usess of Arrays](#usess-of-arrays)
52 | - [Usess of Sets](#usess-of-sets)
53 | - [Usess of Object](#usess-of-object)
54 | - [Usess of Maps](#usess-of-maps)
55 | - [Basic Data Structures](#basic-data-structures)
56 | - [Numbers](#numbers)
57 | - [BigInt](#bigint)
58 | - [Date](#date)
59 | - [Intl NameSpace](#intl-namespace)
60 | - [Loops](#loops)
61 | - [For Loops](#for-loops)
62 | - [For of loops](#for-of-loops)
63 | - [ForEach loops](#foreach-loops)
64 | - [Nested Loops](#nested-loops)
65 | - [While loop](#while-loop)
66 | - [Loop Control Statments](#loop-control-statments)
67 | - [Continue](#continue)
68 | - [Break](#break)
69 | - [Timers](#timers)
70 | - [SetTimeout](#settimeout)
71 | - [setInterval](#setinterval)
72 | - [DOM Manuplication](#dom-manuplication)
73 | - [Accessing Dom Elements](#accessing-dom-elements)
74 | - [Dom traversing](#dom-traversing)
75 | - [Create New DOM Elements](#create-new-dom-elements)
76 | - [Add Elements to the DOM](#add-elements-to-the-dom)
77 | - [Remove Html Element](#remove-html-element)
78 | - [Add/Remove/Toggle/Check Classes](#addremovetogglecheck-classes)
79 | - [Updating Styles Using Dom](#updating-styles-using-dom)
80 | - [Changing the Atributes](#changing-the-atributes)
81 | - [Events in DOM](#events-in-dom)
82 | - [Short Circuiting](#short-circuiting)
83 | - [Nullish Coalescing Operator](#nullish-coalescing-operator)
84 | - [OOPS](#oops)
85 | - [Class](#class)
86 | - [THE 4 FUNDAMENTAL OOP PRINCIPLES](#the-4-fundamental-oop-principles)
87 | - [Abstraction](#abstraction)
88 | - [Encapsulation](#encapsulation)
89 | - [Inheritance](#inheritance)
90 | - [Polymorphism](#polymorphism)
91 | - [Prototypal inheritance](#prototypal-inheritance)
92 | - [3 WAYS OF IMPLEMENTING PROTOTYPAL INHERITANCE IN JAVASCRIPT](#3-ways-of-implementing-prototypal-inheritance-in-javascript)
93 | - [Constructor Function](#constructor-function)
94 | - [Prototypes](#prototypes)
95 | - [THE PROTOTYPE CHAIN](#the-prototype-chain)
96 | - [ES2015 Classes](#es2015-classes)
97 | - [Getters and Setters](#getters-and-setters)
98 | - [Object.create()](#objectcreate)
99 | - [InHertience between Classes](#inhertience-between-classes)
100 | - [Encapsulation](#encapsulation-1)
101 | - [Chaining in Class methods](#chaining-in-class-methods)
102 | - [Class in one Image](#class-in-one-image)
103 | - [SYNCHRONOUS CODE](#synchronous-code)
104 | - [ASYNCHRONOUS CODE](#asynchronous-code)
105 | - [WHAT ARE AJAX CALLS?](#what-are-ajax-calls)
106 | - [WHAT IS AN API?](#what-is-an-api)
107 | - [WHAT HAPPENS WHEN WE ACCESS A WEB SERVER](#what-happens-when-we-access-a-web-server)
108 | - [WHAT ARE PROMISES?](#what-are-promises)
109 | - [Fetch API](#fetch-api)
110 | - [THE PROMISE LIFECYCLE](#the-promise-lifecycle)
111 | - [Building the Promise](#building-the-promise)
112 | - [Async Await Function](#async-await-function)
113 | - [Promise Combinator](#promise-combinator)
114 | - [AN OVERVIEW OF MODULES](#an-overview-of-modules)
115 | - [WHY MODULES?](#why-modules)
116 | - [NATIVE JAVASCRIPT (ES6) MODULES](#native-javascript-es6-modules)
117 | - [HOW ES6 MODULES ARE IMPORTED](#how-es6-modules-are-imported)
118 | - [Import and Export Modules](#import-and-export-modules)
119 | - [Developer Skills](#developer-skills)
120 | - [HOW TO FAIL 🤦 AT LEARNING HOW TO CODE](#how-to-fail--at-learning-how-to-code)
121 | - [HOW TO SUCCEED 🎉 AT LEARNING HOW TO CODE](#how-to-succeed--at-learning-how-to-code)
122 | - [HOW TO FAIL 🤦 AT SOLVING PROBLEMS](#how-to-fail--at-solving-problems)
123 | - [4 STEPS FRAMEWORK TO SOLVE ANY PROBLEM](#4-steps-framework-to-solve-any-problem)
124 | - [WHAT IS A SOFTWARE BUG?](#what-is-a-software-bug)
125 | - [THE DEBUGGING PROCESS](#the-debugging-process)
126 |
127 | ## Basis of JS
128 |
129 | 1. On page Script
130 |
131 | ```html
132 |
135 | ```
136 |
137 | 2. Include external JS file
138 |
139 | ```html
140 |
141 | ```
142 |
143 | 3. Output
144 |
145 | ```js
146 | console.log(a); // write to the browser console
147 | document.write(a); // write to the HTML
148 | alert(a); // output in an alert box
149 | confirm('Really?'); // yes/no dialog, returns true/false depending on user click
150 | prompt('Your age?', '0'); // input dialog. Second argument is the initial value
151 | ```
152 |
153 | 4. Comments
154 |
155 | ```js
156 | /* Multi line
157 | comment */
158 | // One line
159 | ```
160 |
161 | 6. Strict mode
162 |
163 | ```js
164 | 'use strict'; // Use strict mode to write secure code
165 | x = 1; // Throws an error because variable is not declared
166 | ```
167 |
168 | ## The 7 Primitive Data types
169 |
170 | - To check the Data type of any Varible / Value
171 |
172 | ```js
173 | console.log(typeof 'ChandraPrakash');
174 | ```
175 |
176 | - Way of Declaring Variables
177 |
178 | ```js
179 | var a; // variable
180 | var a = 1,
181 | b = 2,
182 | c = a + b; // one line
183 | const PI = 3.14; // constant
184 | let z = 'zzz'; // block scope local variable
185 |
186 | ('use strict'); // Use strict mode to write secure code
187 | x = 1; // Throws an error because variable is not declared
188 | // Creates property on global scope. [Not reccomend to wright Variable without Declaring]
189 | ```
190 |
191 | 1. Number: Floating point numbers -> Used for decimal and integers.
192 |
193 | ```js
194 | let age = 23;
195 | console.log(typeof age);
196 | ```
197 |
198 | 2. String: Sequence of characters -> Used for text.
199 |
200 | ```js
201 | let firstName = 'ChandraPrakash';
202 | console.log(typeof firstname);
203 | ```
204 |
205 | 3. Boolean: Logical type that can only be true or false -> Used for taking decisiions.
206 |
207 | ```js
208 | let fullAge = true;
209 | console.log(typeof fullAge);
210 | ```
211 |
212 | 4. Undefined Value by a variables is not yet defind("empty value").
213 |
214 | ```js
215 | let children;
216 | console.log(typeof children);
217 | ```
218 |
219 | 5. Null: Also means 'empty value'.
220 |
221 | ```js
222 | let myNull = null;
223 | console.log(typeof myNull);
224 | ```
225 |
226 | 6. Symbol (ES2015): Value that is unquie and cannot be changed _[Not useful for now]_.
227 |
228 | 7. Biglnt (ES2020): Larger integers than the Number type can hold.
229 |
230 | ## Operators in JS
231 |
232 | - [Arithmetic Operators](#arithmetic-operators)
233 | - [Assignment Operators](#assignment-operators)
234 | - [Comparison Operators](#comparison-operators)
235 | - [Logical Operators](#logical-operators)
236 | - [Ternary Operators](#ternary-operators)
237 |
238 | ### Arithmetic Operators
239 |
240 | ```js
241 | console.log(10 + 5); // Addition -> 15
242 | console.log(10 - 5); // Subtraction -> 5
243 | console.log(10 / 2); // Division -> 5
244 | console.log(10 * 4); // Multply -> 40
245 | console.log(7 % 2); // Modulas -> 1
246 | console.log(2 ** 4); // 16
247 | console.log(2++); // Increment -> 3
248 | console.log(2--); // Decrement -> 1
249 | ```
250 |
251 | - Post and Pre Increment/Decrement
252 |
253 | ```js
254 | let x = 5;
255 | // x++, it will increase the value of x when the program control goes to the next statement.
256 | // ++x, it will increase the value of x there only
257 |
258 | x++; //post-increment, x will be 5 here and 6 in the next line
259 | ++x; //pre-increment, x will be 7 here
260 | x--; //post-decrement, x will be 7 here and 6 in the next line
261 | --x; //pre-decrement, x will be 5 here
262 | ```
263 |
264 | ### Assignment Operators
265 |
266 | ```js
267 | let x = 10 + 5; // Assigns right operand value to the left operand. -> 15
268 | x += 10; // Sum left and right operand and stores in left operand -> 25
269 | x *= 4; // Multiply left and right operand and stores in left operand -> 100
270 | // [ " -= " for Subtraction , " /= " for Division , " %= " for Modulas ]
271 | x++; // 101
272 | x--; // 100
273 | x--; // 99
274 | console.log(x); // 99
275 | ```
276 |
277 | ### Comparison Operators
278 |
279 | ```js
280 | console.log(40 == 8); // Compares the equality of two operands without considering type.
281 | console.log(40 === 8); // Compares equality of two operands with type.
282 | console.log(40 != 8); // Compares inequality of two operands without considering type.
283 | console.log(40 !== 8); // Compares inequality of two operands with type.
284 | console.log(40 < 8); // Less Than / return true if 40 <> 8
285 | console.log(40 >= 8); // Greater Than equal to / return true if 40 >= 8
286 | console.log(40 <= 8); // Less Than equal to / return true if 40 <>= 8
287 | ```
288 |
289 | ### Logical Operators
290 |
291 | ```js
292 | let a = 5,
293 | b = 10;
294 |
295 | a != b && a < b; // returns true. // Both Condition should true.
296 | a > b || a == b; // returns false // One Condition should true
297 | a < b || a == b; // returns true
298 | !(a < b); // returns false // Inverse the Solution true <-> false
299 | !(a > b); // returns true
300 | ```
301 |
302 | ### Ternary Operators
303 |
304 | The second part (after ? and before :) will be executed if the condition turns out to be true. Suppose, the condition returns false, then the third part (after :) will be executed.
305 |
306 | ```js
307 | let a = 10,
308 | b = 5;
309 |
310 | var c = a > b ? a : b; // value of c would be 10
311 | var d = a > b ? b : a; // value of d would be 5
312 | ```
313 |
314 | ### Spread/Rest Operator
315 |
316 | ```js
317 | // Unpacking Array at Once by spread Operator
318 | const arr = [7, 8, 9];
319 | const badNewArr = [1, 2, arr[0], arr[1], arr[2]]; // [1, 2, 7, 8, 9]
320 |
321 | const newArr = [1, 2, ...arr]; // [1, 2, 7, 8, 9]
322 | // spread operator is comma seprated Value -> It can be Used for all iterable ( string , array , map , sets ) But not Objects
323 | // this are completing new array
324 |
325 | console.log(newArr); // [1, 2, 7, 8, 9]
326 | console.log(...newArr); // 1 2 7 8 9
327 |
328 | // Spread operator on String
329 | const str = 'Jonas';
330 | const letters = [...str, '', 'S.']; // ['J', 'o', 'n', 'a', 's', '', 'S.']
331 |
332 | // Spread operator are only Used when multiple Values can enter... like you can't use in tmeplte litral
333 |
334 | // SPREAD, beacuse it is on RIGHT side of = -> value seprated by commas
335 | const arr = [1, 2, ...[3, 4]];
336 | console.log(arr); // [1, 2, 3, 4]
337 |
338 | // REST, beacuse on LEFT side of = -> variable seprated by Comma
339 | const [a, b, ...others] = [1, 2, 3, 4, 5, 6];
340 | console.log(a, b, others); // 1 2 [3, 4, 5, 6]
341 |
342 | const [pizza, resto, ...otherFood] = [
343 | ...restaurant.mainMenu,
344 | ...restaurant.starterMenu,
345 | ];
346 | console.log(pizza, resto, otherFood); // Pizza Pasta ['Risotto', 'Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad']
347 |
348 | // Objects
349 | const { sat, ...weekdays } = restaurant.openingHours;
350 | console.log(sat, weekdays); // {open: 0, close: 24} {thu: {…}, fri: {…}}
351 |
352 | // FUNCTIONS
353 | const add = function (...numbers) {
354 | let sum = 0;
355 | for (let i = 0; i < numbers.length; i++) sum += numbers[i];
356 | console.log(sum);
357 | };
358 | add(2, 3);
359 | add(2, 3, 4);
360 | add(2, 3, 4, 5);
361 | add(2, 4, 54, 45);
362 |
363 | const x = [2, 5, 1, 51, 54, 54, 5];
364 | add(...x);
365 |
366 | // Copy Array
367 | const myArr = [1, 2, 3];
368 | const myCopy = [...myArr]; // All elemt of myArr will be Copied
369 | ```
370 |
371 | ## Template literals (Template strings)
372 |
373 | ```js
374 | // Untagged, these create strings:
375 | `string text``string text line 1
376 | string text line 2` // Multi line String
377 | `string text ${expression} string text`; // access any veriable by ${variable_name}
378 | ```
379 |
380 | - Without Template Literals
381 |
382 | ```js
383 | let a = 5,
384 | b = 10;
385 | console.log('Fifteen is ' + (a + b) + ' and \n not ' + (2 * a + b) + '.');
386 | // "Fifteen is 15 and
387 | // not 20."
388 | ```
389 |
390 | - With Template Literals
391 |
392 | ```js
393 | let a = 5,
394 | b = 10;
395 | console.log(`Fifteen is ${a + b} and
396 | not ${2 * a + b}.`);
397 | // "Fifteen is 15 and
398 | // not 20."
399 | ```
400 |
401 | ## Conditional Statment ( if-Else )
402 |
403 | ```js
404 | const age = 19;
405 | if (age >= 18) {
406 | // logical condition
407 | status = 'Eligible for driving License.'; // executed if condition is true
408 | } else {
409 | // else block is optional
410 | const yearsLeft = 18 - age;
411 | status = `Not eligible for driving License. Wait for ${yearsLeft} years`;
412 | // executed if condition is false
413 | }
414 | ```
415 |
416 | ## Type Conversion and Coercion
417 |
418 | - [Type Conversion](#type-conversion) Changing type of the Data explicitly.
419 | - [Type Coercion](#type-coercion) Javascript changing type of the Data implicitly.
420 |
421 | ### Type Conversion
422 |
423 | ```js
424 | const inputYear = '1991';
425 | // number() for String to Number
426 | console.log(Number(inputYear), inputYear); // 1991 '1991'
427 | console.log(Number(inputYear) + 18); // 2009
428 |
429 | console.log(Number('ChandraPrakash')); // NaN
430 |
431 | // String() for Number to String
432 | console.log(String(23)); // 23
433 | ```
434 |
435 | #### Falsy values
436 |
437 | [ 0 , "" , undefined , null , NaN , false ] are false if they are converted to Boolean
438 |
439 | ```js
440 | console.log(Boolean(0)); // false
441 | console.log(Boolean('')); // false
442 | console.log(Boolean(NaN)); // false
443 | console.log(Boolean(false)); // false
444 | console.log(Boolean(undefined)); // false
445 | console.log(Boolean(null)); // false
446 | ```
447 |
448 | #### Truely Value
449 |
450 | All values are truely if it is not [ 0 , "" , undefined , null , NaN , false ]
451 |
452 | ### Type Coercion
453 |
454 | ```js
455 | // 23 Automatically converted to String while logging the String.
456 | // " + " convert number to String
457 | console.log('I am ' + 23 + ' years old.'); // I am 23 years old.
458 |
459 | // " - " , " / " , " * " and also logical operators
460 | // convert String to Number
461 | console.log('23' - '10' - 3); // 10
462 | console.log('23' > '10'); // true
463 |
464 | // Example
465 | let n = '1' + 1; // 11
466 | n = n - 1; // 10
467 | console.log(n);
468 | ```
469 |
470 | ## Switch Statment
471 |
472 | ```js
473 | switch (
474 | new Date().getDay() // input is current day
475 | ) {
476 | case 6: // if (day == 6)
477 | text = 'Saturday';
478 | break;
479 | case 0: // if (day == 0)
480 | text = 'Sunday';
481 | break;
482 | default:
483 | // else...
484 | text = 'Whatever';
485 | }
486 | ```
487 |
488 | ## Functions
489 |
490 | ```js
491 | // Function Declaration // Pros we can call Before Declaration
492 | function addNumbers(a, b) {
493 | return a + b;
494 | }
495 | x = addNumbers(1, 2);
496 | console.log(x); // 3
497 |
498 | // Function Expression // Can't call before Declration
499 | const birthYear = 2002;
500 | const calcAge = function (birthYear) {
501 | return 2022 - birthYear;
502 | };
503 | console.log(calcAge(birthYear)); // 20
504 |
505 | // Arow function
506 | const calcAge2 = birthYear => 2022 - birthYear;
507 |
508 | // Arrow functions with more than one Variablea
509 | const yearsUntilRetirment = (birthYear, firstName) => {
510 | const age = 2022 - birthYear;
511 | const retirment = 65 - age;
512 | return `${firstName} retires in ${retirment} years`;
513 | };
514 | console.log(yearsUntilRetirment(2002, 'Chandraprakash'));
515 | ```
516 |
517 | ### Default Arguments
518 |
519 | ```js
520 | const bookings = [];
521 | const createBooking = function (
522 | flightNum,
523 | numPassenger = 1, // default Variables
524 | price = 199 * numPassenger // Using Expression on alredy defined variable
525 | ) {
526 | const booking = {
527 | flightNum, // Direct object declaration
528 | numPassenger,
529 | price,
530 | };
531 | console.log(booking);
532 | bookings.push(booking);
533 | };
534 | createBooking('LH123'); // Passing only one arrgument
535 | createBooking('LH123', 2, 800);
536 | createBooking('LH123', 2); // Calculating price value depending upon passneger
537 | createBooking('LH123', 5);
538 | createBooking('LH123', undefined, 50); // set any value to undefined to skip that value and make it default
539 | console.log(bookings); // Loging all the booking
540 | ```
541 |
542 | ### How passing argument Works :: value vs. Refrence
543 |
544 | ```js
545 | const flight = 'LH123';
546 | const jonas = {
547 | name: 'Jonas Schmendtmann',
548 | passport: 646513132,
549 | };
550 |
551 | const checkIn = function (flightNum, passneger) {
552 | flightNum = 'LH999';
553 | passneger.name = 'Mr.' + passneger.name;
554 |
555 | if (passneger.passport === 646513132) {
556 | // alert('CheckIn');
557 | } else {
558 | // alert('Wrong Passport');
559 | }
560 | };
561 | checkIn(flight, jonas);
562 | console.log(flight, jonas); // LH123 {name: 'Mr.Jonas Schmendtmann', passport: 646513132}
563 |
564 | // When we pass any primitive data type the copy of data is passed
565 | // But When we pass Object in Function the Refrence is passed not the copy with that :::
566 | // when we change in the function it change the refrence and Orignal One Becuse it is Saved in memorry Heap
567 | ```
568 |
569 | ### First Class and Higher Order Function
570 |
571 | - First Class Function => JavaScript treats function as first-class Citizen =>
572 | - This means that functions are simply values =>
573 | - Functions are just another Object
574 | - Just a concept that a Programming Language as or not :::
575 |
576 | #### Some Properties of First-Class Functions
577 |
578 | - **Store Functions in Variables or Properties**
579 |
580 | ```js
581 | const add = (a, b) => a + b;
582 | ```
583 |
584 | ```js
585 | const conuter = {
586 | value: 23,
587 | inc: function () {
588 | this.value++;
589 | },
590 | };
591 | ```
592 |
593 | - **Pass functions as Argumnets to OTHER functions**
594 |
595 | ```js
596 | const greet = () => console.log('hey Chandr Prakash');
597 | btnClose.addEventListener('click', greet);
598 | ```
599 |
600 | - **Return Functon from Function**
601 | - **Call methods on functions:**
602 |
603 | ```js
604 | counter.inc.bind(someOtherObject);
605 | ```
606 |
607 | ### Higher Order Functions
608 |
609 | - A function that **receives** another function as an argument, that **return** a new function, or **both**
610 | - Is in practise when lang => Supports the **First class Function**
611 |
612 | #### Some Properties of Higher-Order Functions
613 |
614 | ##### Function that recevies another function
615 |
616 | ```js
617 | const greet = () => console.log("Hey ChandrPrakash);
618 | btnClose.addEventListener('click', greet)
619 | // addEventListener is a Higher-order function
620 | // greet is CallBack Function
621 | ```
622 |
623 | ##### Function that returns a new function
624 |
625 | ```js
626 | function count() {
627 | // ⇑ Higher Order Function
628 | let counter = 0;
629 | return function () {
630 | // ⇑ Returned Function
631 | counter++;
632 | };
633 | }
634 | ```
635 |
636 | #### Implimentation
637 |
638 | ##### Function Accepting CallBacks
639 |
640 | ```js
641 | const oneWord = function (str) {
642 | return str.replace(/ /g, '').toLowerCase();
643 | };
644 | const upperFirstWord = function (str) {
645 | const [first, ...other] = str.split(' ');
646 | return [first.toUpperCase(), ...other].join(' ');
647 | };
648 |
649 | // Higher Order Functions
650 | const transformer = function (str, fn) {
651 | // fn is callback function
652 | // Higher order Function does not consist of Main logic
653 | // It depend Upon the lower order function
654 | // Higher Order function doesn't know what to do
655 | console.log(`Orignal String: ${str}`);
656 | console.log(`Transformed String: ${fn(str)}`);
657 |
658 | console.log(`Transformed by: ${fn.name}`);
659 | };
660 |
661 | transformer('JavaScript is the Best', upperFirstWord);
662 | // Orignal String: JavaScript is the Best
663 | // Transformed String: JAVASCRIPT is the Best
664 | // Transformed by: upperFirstWord
665 | transformer('JavaScript is the Best', oneWord);
666 | // Orignal String: JavaScript is the Best
667 | // Transformed String: javascriptisthebest
668 | // Transformed by: oneWord
669 |
670 | // Js uses callbacks all the Time
671 | const high5 = function () {
672 | console.log('👋');
673 | };
674 |
675 | document.body.addEventListener('click', high5);
676 | ['Jonas', 'Martha', 'Adam'].forEach(high5);
677 | ```
678 |
679 | ##### Function Returninng the Function
680 |
681 | ```js
682 | // Function Expression
683 | const greetExp = function (greeting) {
684 | return function (name) {
685 | console.log(`${greeting} ${name}`);
686 | };
687 | };
688 | const greetHey = greetExp('Hey');
689 | greetHey('Jonas');
690 | greetHey('Chandraprakash');
691 |
692 | greetExp('Hello')('Chandra Prakash');
693 |
694 | // Arrow Function ( confusing )
695 | const greetArr = greeting => name => console.log(`${greeting} ${name}`);
696 |
697 | greetArr('Hi')('Chandra Prakash');
698 | ```
699 |
700 | ##### Call Method
701 |
702 | ```js
703 | const luthansa = {
704 | airline: 'luthansa',
705 | iataCode: 'LH',
706 | bookings: [],
707 | book(flightNum, name) {
708 | console.log(
709 | `${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}`
710 | );
711 | this.bookings.push({
712 | flight: `${this.iataCode}${flightNum}`,
713 | name,
714 | });
715 | },
716 | };
717 | luthansa.book(234, 'Jonas Schmendtmann');
718 |
719 | const eurowing = {
720 | name: 'Eurowings',
721 | iataCode: 'EW',
722 | bookings: [],
723 | };
724 |
725 | const book = luthansa.book;
726 |
727 | // book(23, 'Sarah Williams'); // Here this keyword in book function will be undefined so it will bring Error
728 | // Book is Just a normal function not and method
729 |
730 | // Call Method
731 | book.call(eurowing, 543, 'Chandraprakash'); // Here we are settings that `this` keyword should point to eurowing
732 |
733 | book.call(luthansa, 654, 'ChandrPrakash');
734 | ```
735 |
736 | ##### Apply Method
737 |
738 | Takes two argument 1. this keyword Point 2. array of argument should pass to book fun.
739 |
740 | ```js
741 | const bookingData = [332, 'Mary Will'];
742 | book.apply(luthansa, bookingData); // Not Used More in Mordern JS
743 | console.log(luthansa);
744 |
745 | // apply alt.
746 | book.call(eurowing, ...bookingData); // Spread Opertaor Convert array to comma Sperated Values
747 | console.log(eurowing);
748 | ```
749 |
750 | ##### Bind Method
751 |
752 | ```js
753 |
754 | // bind method creates new function ::: that functions ""this"" keyword points to the object that is binded
755 | const bookEW = book.bind(eurowing);
756 | bookEW(23, 'Stewen');
757 |
758 | // Giving the default argument to the returned function
759 | const bookEW23 = book.bind(eurowing, 23);
760 | bookEW23('Chandraprakash');
761 |
762 | // Practical Use
763 | luthansa.planes = 300;
764 | luthansa.buyPlane = function () {
765 | console.log(this);
766 |
767 | this.planes++;
768 | console.log(this.planes);
769 | };
770 |
771 | // in Event handler the function passed in always point to the element we are giving event
772 | document.querySelector('.buy').addEventListener('click', luthansa.buyPlane); // NaN
773 |
774 | // We need to give the this keyword manualy
775 | document
776 | .querySelector('.buy')
777 | .addEventListener('click', luthansa.buyPlane.bind(luthansa));
778 | // {airline: 'luthansa', iataCode: 'LH', bookings: Array(3), planes: 300, book: ƒ, …}
779 | // 301
780 |
781 | // Partial Application
782 | const addtax = (rate, value) => value + value \* rate;
783 | console.log(addtax(0.1, 100));
784 |
785 | const addVAT = addtax.bind(null, 0.23);
786 | // addVAT = value => value + value \* .23
787 |
788 | console.log(addVAT(100));
789 | console.log(addVAT(23));
790 |
791 | const addtaxNoBind = function (rate) {
792 | return function (value) {
793 | return value + value \* rate;
794 | };
795 | };
796 |
797 | const rate23 = addtaxNoBind(0.23);
798 | console.log(rate23(100));
799 | console.log(rate23(23));
800 |
801 | ```
802 |
803 | ### Imediately Invoked Functions
804 |
805 | ```js
806 | (function () {
807 | console.log('This Only Run Once');
808 | })();
809 |
810 | (() => {
811 | console.log('Arrow only once');
812 | const isPrivate = 23; // Scoped Variable Cant't Accese from Outside
813 | })();
814 |
815 | {
816 | const isPrivte = 40; // Private blovked Scoped
817 | var notPrivate = 46; // Not Privte Functional Scope
818 | }
819 | ```
820 |
821 | ## Arrays
822 |
823 | ```js
824 | // Methoda 1 of declaring Arrays
825 | const friends = ['Ankit', 'Dave', 'Jonas'];
826 | console.log(friends);
827 |
828 | // Method 2 of Declaring Arrays
829 | const years = new Array(1991, 1992, 1993, 1994, 1995, 1996, 1997);
830 | console.log(years);
831 |
832 | // Access the Elements
833 | console.log(friends[0], years[3]);
834 |
835 | // length of Arrays
836 | console.log(friends.length);
837 |
838 | // Last item of Array
839 | console.log(friends[friends.length - 1]);
840 |
841 | // Changing Element
842 | friends[1] = 'Jay';
843 | console.log(friends);
844 |
845 | // Diffrent type of Data
846 | const chandraPrakash = [
847 | 'ChandraPrakash',
848 | 'Darji',
849 | 2022 - 2002,
850 | 'India',
851 | friends,
852 | ];
853 | console.log(chandraPrakash);
854 |
855 | // Pushing Element
856 | const NewLength = friends.push('C2'); // Element is pushed and NewLenght is Returned
857 | console.log(friends, NewLength);
858 |
859 | // Push Element at index 0
860 | friends.unshift('Raj');
861 | console.log(friends);
862 |
863 | // Remove Element
864 | const popedValue = friends.pop();
865 | console.log(friends, popedValue);
866 |
867 | // Remove first Element
868 | friends.shift();
869 | console.log(friends);
870 |
871 | // find Element
872 | console.log(friends.indexOf('Jay')); // 1
873 | console.log(friends.indexOf('Jay2')); // -1 means not Exist
874 |
875 | // check if exist
876 | console.log(friends.includes('Jay')); // true
877 |
878 | // Distructuring( Unpacking ) the Array
879 | const arr = [2, 3, 4];
880 | const [x, y, z] = arr;
881 | console.log(x, y, z); // 2 3 4
882 |
883 | const categories = ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'];
884 | const [main, , secondary] = categories; // mainn = "IOItalian" and secondary = "Vegetarian"
885 | [secondary, main] = [main, secondary]; // main <-> secondary
886 |
887 | const nested = [2, 3, [4, 5]];
888 | const [i, , [j, k]] = nested;
889 | console.log(i, j, k); // 2 4 5
890 |
891 | const [p, q, r] = [2, 5]; // p = 2 ::: q = 5 ::: r = undefined
892 | const [p = 1, q = 1, r = 1] = [2]; // p = 2 ::: q = 1 ::: r = 1
893 |
894 | // 1. SLICE Method
895 | let arr = ['a', 'b', 'c', 'd', 'f'];
896 | console.log(arr.slice(2)); // element from 2 index to end :: ['c', 'd', 'f']]
897 | console.log(arr.slice(2, 4)); // element from 2 index to 3 ['c', 'd']
898 | console.log(arr.slice(-2)); // negative number means from end of the array :: ['d', 'f']
899 | console.log(arr.slice(2, 4)); // element from 2 index to 3 ['c', 'd']
900 | console.log(arr.slice(2, -2)); // ["c"]
901 | console.log(arr.slice()); // full copy of orignal Array
902 |
903 | // 2. SPLICE
904 | console.log(arr.splice(2)); // [ "c", "d", "f" ]
905 | console.log(arr); // [ "a", "b" ] // Extracted element is removed
906 |
907 | // 3. REVERSE
908 | arr = ['a', 'b', 'c', 'd', 'f'];
909 | let arr2 = ['j', 'k', 'i', 'g'];
910 |
911 | console.log(arr2.reverse()); // Reverse the original array and return it
912 | console.log(arr2); // [ "g", "i", "k", "j" ]
913 |
914 | // 4. CONCAT
915 | const letters = arr.concat(arr2); // Adding 2 array :: didn't change orrignal
916 | console.log(letters); // [ "a", "b", "c", "d", "f", "g", "i", "k", "j" ]
917 |
918 | // 5. JOIN
919 | console.log(letters.join(' - ')); // a - b - c - d - f - g - i - k - j
920 | // Join array items by any seprater
921 | ```
922 |
923 | **Map method**
924 |
925 | Map returns a new array containg the result of pplying operation on all original elements.
926 |
927 | In Map method also like forEach callback function ::: first argument -> element ::: second -> index ::: third argument -> Array.
928 |
929 | ```js
930 | // Map method :: Don't change Orignal Array
931 | const eurToUsd = 1.1;
932 | const moveUsd = movements.map(mov => mov * eurToUsd);
933 |
934 | console.log(movements); // [ 200, 450, -400, 3000, -650, -130, 70, 1300 ]
935 | console.log(moveUsd); // [ 220.00000000000003, 495.00000000000006, -440.00000000000006, 3300.0000000000005, -715.0000000000001, -143, 77, 1430.0000000000002 ]
936 | ```
937 |
938 | **Filter Method**
939 | Filter returns a new array contaning the array elements that passed a specified text condition
940 |
941 | Returns the whole array matches the condition
942 |
943 | ```js
944 | const deposit = movements.filter(mov => mov > 0);
945 | const withdrawal = movements.filter(mov => mov < 0);
946 |
947 | console.log(movements); // [ 200, 450, -400, 3000, -650, -130, 70, 1300 ]
948 | console.log(deposit); // [ 200, 450, 3000, 70, 1300 ]
949 | console.log(withdrawal); // [ -400, -650, -130 ]
950 | ```
951 |
952 | **Find Method** Returns the element that matches the given Condition
953 |
954 | ```js
955 | // FIND Method - returns only first element matchs the condition
956 | let finded = movements.find(mov => mov < 0);
957 | console.log(`First Withdrawal ${finded}`);
958 | ```
959 |
960 | **FindIndex Method** Returns the element that matches the given Condition
961 |
962 | ```js
963 | // FindIndex Method - returns only first index that matchs the condition
964 | let index = movements.findIndex(mov => mov === 200);
965 | console.log(`First 200 Withdrawal was you ${index} transaction`);
966 | ```
967 |
968 | **Some Method** Returns the true/false that when any element matches the given Condition
969 |
970 | ```js
971 | console.log(movements); // [200, 450, -400, 3000, -650, -130, 70, 1300]
972 | // Equality
973 | console.log(movements.includes(-130)); // true
974 |
975 | // Condition
976 | console.log(movements.some(mov => mov > 1500)); // true
977 | ```
978 |
979 | **Every Method** Returns the true/false when all element matches the given Condition
980 |
981 | ```js
982 | // Every Method
983 | console.log(movements.every(mov => mov > 1500)); // false
984 | ```
985 |
986 | **Reduce Method**
987 | Reduce boils("Reduces") all the array elements down to one single value (e.g. adding all the elements together)
988 |
989 | ```js
990 | // REDUCE method
991 | console.log(movements);
992 | const balance = movements.reduce((acc, cur, i, arr) => {
993 | console.log(`Iteration ${i}: Accumulator is ${acc}`);
994 | // acc :: accumulator value saved in acc
995 | // cur :: current number
996 | // i :: index
997 | // arr :: actuall arr
998 | /* Output ::: Iteration 0: Accumulator is 0
999 | Iteration 1: Accumulator is 200
1000 | ...
1001 | Iteration 7: Accumulator is 2540
1002 | */
1003 | return acc + cur;
1004 | }, 0);
1005 | console.log(balance); // 3840
1006 |
1007 | // Finding Max Number
1008 | console.log(movements); // [ 200, 450, -400, 3000, -650, -130, 70, 1300 ]
1009 | const maxMov = movements.reduce(
1010 | (acc, cur) => (acc > cur ? acc : cur),
1011 | movement[0]
1012 | );
1013 | console.log(maxMov); // 3000
1014 | ```
1015 |
1016 | **Flat Method** Remve Nesting from Array
1017 |
1018 | ```js
1019 | const arr = [[1, 2, 3], [4, 5, 6], 7, 8, 9];
1020 | console.log(arr.flat()); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
1021 |
1022 | const arrDeep = [
1023 | [1, 2, 3],
1024 | [4, 5, 6, [7, 8, 9, [0]]],
1025 | ];
1026 | console.log(arrDeep.flat()); // [1, 2, 3, 4, 5, 6, Array(4)]
1027 | // Only flat till level 1
1028 | console.log(arrDeep.flat(2)); //[1, 2, 3, 4, 5, 6, 7, 8, 9, Array(1)]
1029 | console.log(arrDeep.flat(10)); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
1030 | ```
1031 |
1032 | **Flatmap Method** Map Every element of array and then flat at the same time. Flat map only flat till level 1.
1033 |
1034 | ```js
1035 | const accc = [
1036 | {
1037 | owner: 'Jonas Schmedtmann',
1038 | movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
1039 | },
1040 | {
1041 | owner: 'Jessica Davis',
1042 | movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
1043 | },
1044 | {
1045 | owner: 'Steven Thomas Williams',
1046 | movements: [200, -200, 340, -300, -20, 50, 400, -460],
1047 | },
1048 | {
1049 | owner: 'Sarah Smith',
1050 | movements: [430, 1000, 700, 50, 90],
1051 | },
1052 | ];
1053 | const balance = accc
1054 | .flatMap(acount => acount.movements)
1055 | .reduce((acc, val) => acc + val, 0);
1056 | console.log(balance); // 17840
1057 | ```
1058 |
1059 | **Sorting the Array**
1060 |
1061 | ```js
1062 | const owners = ['Jonas', 'Zach', 'Chandraprakash', 'Charli'];
1063 | console.log(owners); // ['Jonas', 'Zach', 'Chandraprakash', 'Charli']
1064 |
1065 | console.log(movements); // [200, 450, -400, 3000, -650, -130, 70, 1300]
1066 |
1067 | movements.sort();
1068 |
1069 | console.log(movements); // [-130, -400, -650, 1300, 200, 3000, 450, 70]
1070 | // Sort the numbers as they are strings not as number
1071 |
1072 | movements.sort((a, b) => (a > b ? 1 : -1));
1073 | // if a > b then it will return 1 => means swap the numbers
1074 | // vice-versa b > a then return -1 => means not swap
1075 | console.log(movements); // [-650, -400, -130, 70, 200, 450, 1300, 3000]
1076 |
1077 | // to change accending to decending just change the condition or the return value
1078 | // you can give any value in place of -1 or 1 value should be positive or negative
1079 |
1080 | movements.sort((a, b) => b - a);
1081 | console.log(movements); // [3000, 1300, 450, 200, 70, -130, -400, -650]
1082 | // Here b - a will be positive when b > a and positive value means swap the number and all will organize in decending order
1083 | ```
1084 |
1085 | **More Ways of creating and Filling Array**
1086 |
1087 | ```js
1088 | // Filling items in array
1089 | //Creating array manually
1090 | const x = new Array(7);
1091 | console.log(x); // Array(7) [ <7 empty slots> ]
1092 | // Empty Array with 7 slot
1093 |
1094 | // On these array we can only use
1095 | x.fill(2);
1096 | console.log(x); // [ 2, 2, 2, 2, 2, 2, 2 ]
1097 |
1098 | // FILL method can be use on any array
1099 | x.fill(1, 3, 6);
1100 | console.log(x); // [ 2, 2, 2, 1, 1, 1, 2 ]
1101 | // Mutate the orignal array 1st param: what to fill 2nd params: from where to fill 3rd params: till what :: it will fill till end - 1
1102 |
1103 | // Araay.from
1104 | const y = Array.from({ length: 7 }, () => 1);
1105 | console.log(y); // [ 1, 1, 1, 1, 1, 1, 1 ]
1106 |
1107 | const z = Array.from({ length: 7 }, (_, i) => i + 1);
1108 | console.log(z); // [ 1, 2, 3, 4, 5, 6, 7 ]
1109 |
1110 | const movementUI = Array.from(document.querySelectorAll('.movements__value'));
1111 | console.log(movementUI); // Array(8) [ div.movements__value, .... , div.movements__value ]
1112 |
1113 | // MovementUI is Now array we can easily perform method like map or the reduce
1114 | console.log(movementUI.map(el => Number(el.textContent.replace('€', '')))); //[ 1300, 70, -130, -650, 3000, -400, 450, 200 ]
1115 |
1116 | // Second Arrgument in Array.from is mapping call back that you no need to map sepratly
1117 | const movementUI2 = Array.from(
1118 | document.querySelectorAll('.movements__value'),
1119 | el => Number(el.textContent.replace('€', ''))
1120 | );
1121 | // directly got the array
1122 | console.log(movementUI2); // [ 1300, 70, -130, -650, 3000, -400, 450, 200 ]
1123 | ```
1124 |
1125 | **Which Method When to Use**
1126 |
1127 | > What I Actually Want...
1128 |
1129 | 1. To Mutate original Array
1130 |
1131 | - Add to Original:
1132 | > .push (end)
1133 | > .unshift (start)
1134 | - Remove from Original
1135 | > .pop (end)
1136 | > .shift (start)
1137 | > .splice (any)
1138 | - Others
1139 | > .reverse
1140 | > .sort
1141 | > .fill
1142 |
1143 | 2. A new Array
1144 |
1145 | - Computed from Original
1146 | > .map (loop)
1147 | - Filteres using condition
1148 | > .filter
1149 | - Portion of Original
1150 | > .slice
1151 | - Adding original to other
1152 | > .concat
1153 | - Flattening the original
1154 | > .flat
1155 | >
1156 | > .flatMap
1157 |
1158 | 3. An Array index
1159 |
1160 | - Based on value:
1161 | > .indexOf
1162 | - Based on test condition:
1163 | > .findIndex
1164 |
1165 | 4. An array Element
1166 | - Based on test condition:
1167 | > .find
1168 | 5. Know if array includes
1169 |
1170 | - Based on value:
1171 | > .includes
1172 | - Based on test condition:
1173 | > .some
1174 | >
1175 | > .every
1176 |
1177 | 6. A new String
1178 |
1179 | - Based on separator string:
1180 | > .join
1181 |
1182 | 7. To transform to value
1183 | - Based on accumulator:
1184 | > .reduce (Boil down array to single .filter .findIndex .some (loop) value of any type: number, string, boolean, or even new array or object)
1185 | 8. To jusst loop array
1186 | - Based on callback:
1187 | > .forEach (Does not create a new array, just loops over it)
1188 |
1189 | ## Objects
1190 |
1191 | ```js
1192 | const chandraPrakash = {
1193 | firstName: 'ChandraPrakah',
1194 | lastName: 'Darji',
1195 | age: 2022 - 2002,
1196 | job: 'Student',
1197 | languages: ['JavaScript0', 'Python', 'Html', 'CSS'],
1198 | drivingLicense: false,
1199 | // can also hold a function beacuse function is a datatype
1200 | calcAge: function (birthYear) {
1201 | return 2022 - birthYear;
1202 | },
1203 | calcAgeThis: function () {
1204 | return 2022 - this.birthYear; // Takes value from object
1205 | },
1206 | getSummary: function () {
1207 | console.log(
1208 | `${this.firstName} is a ${
1209 | this.job
1210 | } of ${this.calcAgeThis()} learnig today ${this.languages[0]} with ${
1211 | this.drivingLicense ? 'a' : 'no'
1212 | } driving License`
1213 | );
1214 | },
1215 | };
1216 | console.log(chandraPrakash);
1217 |
1218 | // Calling function
1219 | console.log(chandraPrakash.calcAge(2002));
1220 | console.log(chandraPrakash.calcAgeThis());
1221 | chandraPrakash.getSummary();
1222 |
1223 | // Accesing Element
1224 | console.log(chandraPrakash.firstName); // Dot Notation
1225 | console.log(chandraPrakash['job']); // Bracket Notation
1226 |
1227 | // In Bracket Notation Expresion are Allowded
1228 | const nameKey = 'Name';
1229 | console.log(chandraPrakash['first' + nameKey]);
1230 | console.log(chandraPrakash['last' + nameKey]);
1231 |
1232 | // Adding a Element in Objects
1233 | chandraPrakash.location = 'india';
1234 | chandraPrakash['twitter'] = '@chandra_7852';
1235 |
1236 | // Copying the Object
1237 | const jessica = {
1238 | firstName: 'Jessica',
1239 | lastName: 'Willams',
1240 | age: 27,
1241 | };
1242 | const jessicaMarried = jessica;
1243 | console.log(jessica); // {firstName: 'Jessica', lastName: 'Willams', age: 27}
1244 | console.log(jessicaMarried); // {firstName: 'Jessica', lastName: 'Willams', age: 27}
1245 | jessicaMarried.lastName = 'Dave';
1246 | console.log(jessica); // {firstName: 'Jessica', lastName: 'Dave', age: 27}
1247 | console.log(jessicaMarried); // {firstName: 'Jessica', lastName: 'Dave', age: 27}
1248 | // this will essentially just point to same object ... same object with diffrent names ...
1249 | const jessica2 = {
1250 | firstName: 'Jessica',
1251 | lastName: 'Willams',
1252 | age: 27,
1253 | family: ['Bob', 'Steven'],
1254 | };
1255 | const jessica2Married = Object.assign({}, jessica2);
1256 | console.log(jessica2); // {firstName: 'Jessica', lastName: 'Willams', age: 27}
1257 | console.log(jessica2Married); // {firstName: 'Jessica', lastName: 'Willams', age: 27}
1258 | jessica2Married.lastName = 'Dave';
1259 | console.log(jessica2); // {firstName: 'Jessica', lastName: 'Willams', age: 27}
1260 | console.log(jessica2Married); // {firstName: 'Jessica', lastName: 'Dave', age: 27}
1261 | // This will create new object by combining 2 Objects ...
1262 |
1263 | jessica2Married.family.push('Mary', 'John');
1264 | console.log(jessica2); // {firstName: 'Jessica', lastName: 'Willams', age: 27, family: Array(4)}
1265 | console.log(jessica2Married); // {firstName: 'Jessica', lastName: 'Willams', age: 27, family: Array(4)}
1266 | // Object.assign only work for first level... in this Both object array is changed ...
1267 | // to copy prefectly you need to do deep clone
1268 |
1269 | // Destrucutring Object
1270 | const restaurant = {
1271 | name: 'Classico Italiano',
1272 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
1273 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
1274 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
1275 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
1276 |
1277 | openingHours: {
1278 | thu: {
1279 | open: 12,
1280 | close: 22,
1281 | },
1282 | fri: {
1283 | open: 11,
1284 | close: 23,
1285 | },
1286 | sat: {
1287 | open: 0, // Open 24 hours
1288 | close: 24,
1289 | },
1290 | },
1291 | order: function (starterIndex, mainIndex) {
1292 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
1293 | },
1294 | orderDelivery: function ({
1295 | starterIndex = 0,
1296 | mainIndex = 1,
1297 | time = '20:00',
1298 | address,
1299 | }) {
1300 | console.log(
1301 | `Order Recived! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
1302 | );
1303 | },
1304 | orderPasta: function (ing1, ing2, ing3) {
1305 | console.log(
1306 | `Here is Your delecious Pasta with ${ing1} , ${ing2} and ${ing3} ::: `
1307 | );
1308 | },
1309 | };
1310 | const { name, openingHours, categories } = restaurant;
1311 | console.log(name, openingHours, categories); // variable name should exactly same as in Object
1312 | const {
1313 | // Unpacking with diffrent variable Name
1314 | name: restaurantName,
1315 | openingHours: hours,
1316 | categories: tags,
1317 | breakMenu: menu = 'No Data', // default value if data no Exist
1318 | } = restaurant;
1319 | console.log(restaurantName, hours, tags, breakMenu);
1320 |
1321 | // Mutating variables
1322 | let a = 10,
1323 | b = 20;
1324 | const obj = { a: 42, b: 65, c: 86 };
1325 | ({ a, b } = obj);
1326 | console.log(a, b);
1327 |
1328 | // Nested Objects
1329 | // Method 1
1330 | const { open: openFri, close: closeFri } = openingHours.fri;
1331 | console.log(openFri, closeFri);
1332 | // Method 2
1333 | const {
1334 | openingHours: {
1335 | fri: { open: o, close: c },
1336 | },
1337 | } = restaurant;
1338 | console.log(o, c);
1339 |
1340 | // Unpacking Use in Functions -> no More variable to specifiy as pparameter just one object -> then it will be unpacked
1341 | restaurant.orderDelivery({
1342 | time: '22:30',
1343 | address: '402, Saheli Tailor',
1344 | mainIndex: 2,
1345 | starterIndex: 2,
1346 | });
1347 | restaurant.orderDelivery({
1348 | address: '402, Saheli Tailor',
1349 | });
1350 |
1351 | // Spread Oprator in Object Use
1352 | const ingredient = [
1353 | prompt("Let's make Pasta! Ingredient 1:"),
1354 | prompt('Ingredient 2:'),
1355 | prompt('Ingredient 3:'),
1356 | ];
1357 | // Both will work
1358 | restaurant.orderPasta(ingredient[0], ingredient[1], ingredient[2]);
1359 | restaurant.orderPasta(...ingredient);
1360 | // Spread operator will work Better
1361 |
1362 | // ES2018 we can use ... spread opertor on Objects
1363 | const newRestaurant = { ...restaurant, founder: 'Gessiuf', founderYear: 1994 };
1364 | console.log(newRestaurant);
1365 |
1366 | // Copying the Object
1367 | const restaurantCopy = { ...restaurant };
1368 | restaurantCopy.name = 'Ristornos Roma';
1369 | console.log(restaurantCopy);
1370 |
1371 | // Enhanced object litteral
1372 | const weekdays = ['mon', 'tue', 'wed', 'thu', 'sat', 'sun'];
1373 |
1374 | const openingHours = {
1375 | // property name can be modified now by expression
1376 | [weekdays[3]]: {
1377 | open: 12,
1378 | close: 22,
1379 | },
1380 | [weekdays[4]]: {
1381 | open: 11,
1382 | close: 23,
1383 | },
1384 | [weekdays[5]]: {
1385 | open: 0,
1386 | close: 24,
1387 | },
1388 | [`day ${1 + 2 + 3}`]: {
1389 | open: 8,
1390 | close: 22,
1391 | },
1392 | };
1393 | const school = {
1394 | schoolName: 'Mark Socitey',
1395 | hours, // ES6 enhanced object literal
1396 | sorderPasta(ing1, ing2, ing3) {
1397 | // no need for function keyword and semi colon
1398 | console.log(
1399 | `Here is Your delecious Pasta with ${ing1} , ${ing2} and ${ing3} ::: `
1400 | );
1401 | },
1402 | };
1403 | console.log(school);
1404 |
1405 | // Without optional chaining
1406 | if (restaurant.openingHours && restaurant.openingHours.mon)
1407 | console.log(restaurant.openingHours.mon.open);
1408 |
1409 | console.log(restaurant.openingHours.mon.open); // with throw the error of Cannot read properties of undefined (reading 'open')
1410 |
1411 | // WITH Opetional Chaining
1412 | console.log(restaurant.openingHours.mon?.open); // here it wil check if restaurant.openingHours.mon it exist then and only the .openn will bw readed
1413 |
1414 | ////////////////////////////////////
1415 | // Without optional chaining
1416 | if (restaurant.openingHours && restaurant.openingHours.mon)
1417 | console.log(restaurant.openingHours.mon.open);
1418 |
1419 | console.log(restaurant.openingHours.mon.open); // with throw the error of Cannot read properties of undefined (reading 'open')
1420 |
1421 | // WITH Opetional Chaining
1422 | console.log(restaurant.openingHours.mon?.open); // here it wil check if restaurant.openingHours.mon it exist then and only the .openn will bw readed
1423 | console.log(restaurant.openingHours?.mon?.open);
1424 | */
1425 | // Examples
1426 | const days = ['mon', 'tue', 'wed', 'thu', 'sat', 'sun'];
1427 | for (const day of days) {
1428 | const open = restaurant.openingHours?.[day]?.open ?? `closed`;
1429 | console.log(`On ${day} we open at ${open}`);
1430 | /* Output ::: On mon we open at closed
1431 | On tue we open at closed
1432 | On wed we open at closed
1433 | On thu we open at 12
1434 | On sat we open at 11
1435 | On sun we open at 0
1436 | */
1437 | }
1438 | // Methods
1439 | console.log(restaurant.order?.(0, 1) ?? `Method does not exist`); // ['Focaccia', 'Pasta']
1440 | console.log(restaurant.orderRissato?.(0, 1) ?? `Method does not exist`);
1441 |
1442 |
1443 | //////////////////////////////////////
1444 | // Looping the Objects
1445 | // Display Keys only
1446 | const properties = Object.keys(openingHours);
1447 | console.log(properties);
1448 |
1449 | let openStr = `We are open o ${properties.length} days: `;
1450 | for (const day of properties){
1451 | openStr+=`${day}, `
1452 | }
1453 | console.log(openStr);
1454 |
1455 | // Property VALUES
1456 | const values = Object.values(openingHours)
1457 | console.log(values);
1458 |
1459 | // Entire Object
1460 | const entries = Object.entries(openingHours)
1461 | console.log(entries);
1462 |
1463 | for (const [day, {open,close}] of Object.entries(openingHours)){
1464 | console.log(`On ${day} we open at ${open} and close at ${close}`);
1465 | }
1466 | ```
1467 |
1468 | ## Sets
1469 |
1470 | ```js
1471 | const ordersSets = new Set([
1472 | // To create Set
1473 | 'Pasta',
1474 | 'pizza',
1475 | 'Pizza',
1476 | 'Vada Pav',
1477 | 'Pizza',
1478 | 'Pasta',
1479 | ]);
1480 | console.log(ordersSets);
1481 |
1482 | console.log(new Set('ChandraPrakash')); // Can Pass Any Iterable
1483 | console.log(new Set('the quick brown fox jumps over a lazy dog'));
1484 |
1485 | console.log(ordersSets.size); // Size of Set
1486 | console.log(ordersSets.has('Pizza')); // Check for Element
1487 | ordersSets.add('Garlic Bread'); // Add an element
1488 | ordersSets.add('Garlic Bread');
1489 | ordersSets.delete('Vada Pav'); // delete an elemnet
1490 | console.log(ordersSets);
1491 |
1492 | for (const order of ordersSets) console.log(order); // itreating to set through for-of loop
1493 |
1494 | ordersSets.clear(); // To clear the Set
1495 | console.log(ordersSets);
1496 | ```
1497 |
1498 | ## Maps
1499 |
1500 | ```js
1501 | // Maps Fundamental
1502 | const rest = new Map(); // create a MAP
1503 | rest.set('name', 'Classico Italiano'); // Add a element
1504 | rest.set(1, 'Firenze, Italy');
1505 | rest.set(2, 'Lisbon, Portugal');
1506 |
1507 | rest.set('categories', ['Italian', 'Pizzeria', 'Vegetarian', 'Organic']) // Adding Mmultiple Element
1508 | .set('open', 11)
1509 | .set('close', 23)
1510 | .set(true, 'We are opeb :D')
1511 | .set(false, 'We are closed :(');
1512 | console.log(rest);
1513 | console.log(rest.get('name')); // Accesing the Element // Classico Italiano
1514 | console.log(rest.get(true)); // We are opeb :D
1515 | console.log(rest.get(1)); // Firenze, Italy
1516 |
1517 | const time = 21;
1518 | console.log(rest.get(time > rest.get('open') && time < rest.get('close'))); // We are opeb :D
1519 |
1520 | console.log(rest.has('categories')); // true
1521 | rest.delete(2); // delete an element
1522 | const arr = [1, 2, 3];
1523 | rest.set(arr, 'Test'); // Arr should be a variable
1524 | console.log(rest.get(arr));
1525 | console.log(rest); // test
1526 | // rest.clear() // clear the map
1527 | console.log(rest.size); // Size of the MAP
1528 |
1529 | // Itreation through Map
1530 | const question = new Map([
1531 | ['question', 'What is the best programming languange in the world?'],
1532 | [1, 'C'],
1533 | [2, 'Java'],
1534 | [3, 'JavaScript'],
1535 | ['correct', 3],
1536 | [true, 'Correct 🎉'],
1537 | [false, 'Try again! 🤦'],
1538 | ]);
1539 | console.log(question);
1540 |
1541 | // Convert Object to Map
1542 | console.log(Object.entries(openingHours));
1543 | const hoursMap = new Map(Object.entries(openingHours));
1544 | console.log(hoursMap);
1545 |
1546 | // Quiz App
1547 | console.log(question.get('question'));
1548 | // Itreation
1549 | for (const [key, value] of question) {
1550 | if (typeof key === 'number') console.log(`Answer ${key}: ${value}`);
1551 | }
1552 | // const answer = Number(prompt("Enter Your Answer. 1 , 2 or 3"))
1553 | const answer = 3;
1554 | console.log(question.get(answer === question.get('correct')));
1555 |
1556 | // Convert map to Arr
1557 | console.log([...question]);
1558 | console.log([...question.entries()]);
1559 | console.log([...question.keys()]);
1560 | console.log([...question.values()]);
1561 | ```
1562 |
1563 | ## Working With String
1564 |
1565 | ```js
1566 | // Working With String
1567 | const airline = 'TAP Air Portugal';
1568 |
1569 | // Accesing the character with indexing
1570 | console.log(airline[0]); // T
1571 | console.log(airline[1]); // A
1572 | console.log(airline[2]); // P
1573 |
1574 | // to infd the lenght of String
1575 | console.log(airline.length); // 16
1576 |
1577 | // To find the index of Character
1578 | console.log(airline.indexOf('r')); // 6
1579 | console.log(airline.lastIndexOf('r')); // 10
1580 | console.log(airline.indexOf('Portugal')); // 8
1581 |
1582 | // to Slice the charater
1583 | console.log(airline.slice(4)); // one Argument = start
1584 | console.log(airline.slice(0, 4)); // two argument = start,end
1585 | console.log(airline.slice(-8)); // Counting from ending
1586 |
1587 | // Sreing are also Objects that are converted to object when method is called
1588 | console.log(new String('Jonas'));
1589 | console.log(typeof new String('Jonas'));
1590 |
1591 | console.log(airline.toLowerCase()); // Lower casw
1592 | console.log(airline.toUpperCase()); // Upper case
1593 |
1594 | // Fixing Capitilaziation of name
1595 | const fixName = function (peopleName) {
1596 | return peopleName.toUpperCase()[0] + peopleName.toLowerCase().slice(1);
1597 | };
1598 | console.log(fixName('ChaNDRAPrakASH'));
1599 |
1600 | // To Comparing user email
1601 | const email = 'hello@chandraprakash.com';
1602 | const loginEmail = ' HeLLo@ChanDRApraKash.Com \n';
1603 |
1604 | const proccesedEmail = loginEmail.toLowerCase().trim();
1605 | console.log(proccesedEmail === email && 'Login Email is valid');
1606 | console.log(proccesedEmail);
1607 |
1608 | // Replacing part of String
1609 | const priceGB = '288,56£';
1610 | const priceUS = priceGB.replace('£', '$').replace(',', '.');
1611 | console.log(priceUS);
1612 |
1613 | const announcment = 'All passenger come boarding door 23. Boarding door 23!';
1614 |
1615 | console.log(announcment.replace('door', 'gate')); // Change only the first Occurence
1616 | // console.log(announcment.replaceAll('door', 'gate')); // Method gonna come in the Future
1617 | console.log(announcment.replace(/door/g, 'gate')); // Change with the Regular Expression to Change All Occurence
1618 |
1619 | // Bollean
1620 | const plane = 'Airbus A320neo';
1621 | console.log(plane.includes('A320')); // true
1622 | console.log(plane.includes('blue')); // false
1623 | console.log(plane.startsWith('Air')); // true
1624 |
1625 | if (plane.startsWith('Airbus') && plane.endsWith('neo')) {
1626 | console.log('Part of NEW Airbus Family.🙂');
1627 | }
1628 |
1629 | // Practise Exersise
1630 | const checkBaggage = function (items) {
1631 | items = items.toLowerCase();
1632 | if (items.includes('gun') || items.includes('knife')) {
1633 | console.log('Your Not Allowed. 💥');
1634 | } else {
1635 | console.log('You can Board. 🙂');
1636 | }
1637 | };
1638 | checkBaggage('I have a laptop, Some Food and a pocket Knife');
1639 | checkBaggage('Socks and Camera');
1640 | checkBaggage('Got some snacks and a gun for protection');
1641 |
1642 | // Spliting the String
1643 | console.log('a+very+nice+string+by+made+with+plus+sign'.split('+')); // ['a', 'very', 'nice', 'string', 'by', 'made', 'with', 'plus', 'sign']
1644 |
1645 | const [firstName, lastName] = 'Chandrprakash Darji'.split(' ');
1646 | const newName = ['Mr.', firstName, lastName.toUpperCase()].join(' '); // Mr. Chandrprakash DARJI
1647 | console.log(newName);
1648 |
1649 | const capitalizeName = function (name) {
1650 | name = name.split(' ');
1651 | name.forEach(nam => {
1652 | // name[name.indexOf(nam)] = nam[0].toUpperCase() + nam.slice(1).toLowerCase(); // Make to Parts and Capitalized
1653 | name[name.indexOf(nam)] = nam.replace(nam[0], nam[0].toUpperCase()); // replacing first Character ...
1654 | });
1655 | console.log(name.join(' '));
1656 | };
1657 | capitalizeName('jessica ann smith davis');
1658 | capitalizeName('chandrprakash darji');
1659 |
1660 | // padding String
1661 | const message = 'Go to Gate no. 23';
1662 | console.log(message.padStart(20, '+').padEnd(30, '+')); // +++Go to Gate no. 23++++++++++
1663 | console.log('ChandrPrakash'.padStart(20, '+').padEnd(30, '+')); // +++++++ChandrPrakash++++++++++
1664 |
1665 | // Exapmle
1666 | const maskCreditCard = function (number) {
1667 | const str = number + '';
1668 | return str.slice(-4).padStart(str.length, '*');
1669 | };
1670 | console.log(maskCreditCard(6548736)); // ***8736
1671 | console.log(maskCreditCard(46557895613266)); // **********3266
1672 | console.log(maskCreditCard('4655789613264659876')); // ***************9876
1673 |
1674 | const badWaeatherMsg = 'Bad weather... All Ddepartues Delayed... ';
1675 | console.log(badWaeatherMsg.repeat(5)); // Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed... Bad weather... All Ddepartues Delayed...
1676 |
1677 | const planeInLine = function (n) {
1678 | console.log(`There are ${n} planes in line... ${'✈️'.repeat(n)}`);
1679 | };
1680 | planeInLine(5); // There are 5 planes in line... ✈️✈️✈️✈️✈️
1681 | planeInLine(12); // There are 12 planes in line... ✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️✈️
1682 | planeInLine(2); // There are 2 planes in line... ✈️✈️
1683 |
1684 | // Practise Question to Understand String Methods
1685 | const flights =
1686 | '_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30';
1687 |
1688 | const getCode = str => str.slice(0, 3).toUpperCase();
1689 |
1690 | flights.split('+').forEach(flightEntrie => {
1691 | let [status, fromPoint, toPoint, time] = flightEntrie.split(';');
1692 |
1693 | const outPut = `${
1694 | status.startsWith('_Delayed') ? '🔴' : ''
1695 | }${status.replaceAll('_', ' ')} from ${getCode(fromPoint)} to ${getCode(
1696 | toPoint
1697 | )} (${time.replace(':', 'h')})`.padStart(45);
1698 | console.log(outPut);
1699 |
1700 | /*Output --->> 🔴 Delayed Departure from FAO to TXL (11h25)
1701 | Arrival from BRU to FAO (11h45)
1702 | 🔴 Delayed Arrival from HEL to FAO (12h05)
1703 | Departure from FAO to LIS (12h30)
1704 | */
1705 | });
1706 | ```
1707 |
1708 | ## Data Strucutres
1709 |
1710 | ### List of data Strucures
1711 |
1712 | - [Arrays](#arrays)
1713 | - [Objects](#objects)
1714 | - [Sets](#sets)
1715 | - [Maps](#maps)
1716 |
1717 | ### Sources of Data
1718 |
1719 | 1. **From the Program itself:** Data written directly in source code (e.g. status messages)
1720 | 2. **From the UI:** Data input from user or the data written in DOM (e.g. tasks in todo app)
1721 | 3. **From external sources:** Data fetched for example from web API (e.g. recipe objects)
1722 |
1723 | **->** Collection of data **->** Data Structures **->** 1. Simple List [ ARRAYS or SETS] && 2. Key/Value Pairs [OBJECTS or MAPS] (keys allow us to decribe values )
1724 |
1725 | ### Usess of Arrays
1726 |
1727 | - ```js
1728 | const task = ['eat', 'code', 'sleep', 'repeat'];
1729 | ```
1730 |
1731 | - Use when you need ordered list of values (might contain duplicates)
1732 | - Use when you need to manipulate data
1733 |
1734 | ### Usess of Sets
1735 |
1736 | - ```js
1737 | const = new Set(['eat', 'code', 'sleep', 'repeat']);
1738 | ```
1739 |
1740 | - Use when you need to work with unique values
1741 | - Use when high-performance is really important
1742 | - Use to remove duplicates from arrays
1743 |
1744 | ### Usess of Object
1745 |
1746 | - ```js
1747 | const task = {
1748 | task: 'code',
1749 | date: 'today',
1750 | repeat: true,
1751 | };
1752 | ```
1753 |
1754 | - More “traditional” key/value store (“abused” objects)
1755 | - Easier to write and access values with . and []
1756 | - Use when you simply need to map key to values
1757 | - Use when you need keys that are not strings
1758 | - Use when you need to include functions (methods)
1759 | - Use when working with JSON (can convert to map)
1760 |
1761 | ### Usess of Maps
1762 |
1763 | - ```js
1764 | const task = new Map([
1765 | ['task', 'Code'],
1766 | ['date', 'today'],
1767 | [false, 'Start Coding'],
1768 | ]);
1769 | ```
1770 |
1771 | - Better performance
1772 | - Keys can have any data type
1773 | - Easy to iterate
1774 | - Easy to compute size
1775 | - Use when you simply need to map key to values
1776 | - Use when you need keys that are not strings
1777 |
1778 | ### Basic Data Structures
1779 |
1780 | #### Numbers
1781 |
1782 | ```js
1783 | console.log(23 === 23.0); // true
1784 | // Real life Numbers are Base 10 // 0-9
1785 | // Js - Binary Base 2 // 0-1
1786 |
1787 | console.log(0.1 + 0.2); // 0.30000000000000004
1788 | console.log(0.1 + 0.2 === 0.3); // false
1789 |
1790 | // String to Number
1791 | console.log(Number('23'));
1792 | console.log(+'23');
1793 |
1794 | // Parsing => Remove any Alpha But should start from number
1795 | console.log(Number.parseInt('30px')); // 30
1796 | console.log(Number.parseInt('e30px')); // NaN
1797 |
1798 | console.log(Number.parseInt('2.5rem')); // 2
1799 | console.log(Number.parseFloat('2.5rem')); // 2.5
1800 |
1801 | // Number is Global No need to Wright Number
1802 | console.log(parseInt('3rem')); // 3
1803 |
1804 | // Check if Value is Not a number => Value can be anything but NaN
1805 | console.log(Number.isNaN(20)); // false
1806 | console.log(Number.isNaN('20')); // false
1807 | console.log(Number.isNaN('20X')); // false
1808 | console.log(Number.isNaN(+'20X')); // true
1809 | console.log(Number.isNaN(20 / 0)); // false
1810 |
1811 | // Check if value is Number
1812 | console.log(Number.isFinite(20)); // true
1813 | console.log(Number.isFinite('20')); // false
1814 | console.log(Number.isFinite('20X')); // false
1815 | console.log(Number.isFinite(20 / 0)); // false
1816 |
1817 | //Check if Number is intergger or Not
1818 | console.log(Number.isInteger(20)); // true
1819 | console.log(Number.isInteger(20.0)); // true
1820 | console.log(Number.isInteger(20 / 0)); // false
1821 |
1822 | console.log(Math.sqrt(25)); // 5 Square Root
1823 | console.log(25 ** (1 / 2)); // 5
1824 | console.log(8 ** (1 / 3)); // 2
1825 |
1826 | // Max and Min Value
1827 | console.log(Math.max(3, 4, 12, 47, 54, 2, 23, 43, 55, 35, 45)); // 55
1828 | console.log(Math.max(3, 4, 12, 47, '54', 2, 23, 43, 55, 35, 45)); // 55
1829 | console.log(Math.max(3, 4, 12, 47, '54px', 2, 23, 43, 55, 35, 45)); // NaN
1830 | console.log(Math.min(3, 4, 12, 47, 54, 2, 23, 43, 55, 35, 45)); // 2
1831 |
1832 | console.log(Math.PI); // 3.141592653589793
1833 |
1834 | console.log(Math.trunc(Math.random() * 6) + 1); // any Number from 1 to 6
1835 |
1836 | const randomInt = (min, max) =>
1837 | Math.floor(Math.random() * (max - min) + 1) + min; // generalized Function for random Number
1838 |
1839 | console.log(Math.trunc(34.343267)); // 34 removes value after deciaml point
1840 |
1841 | console.log(Math.round(25.3)); // 25 // round the Number
1842 | console.log(Math.round(25.9)); // 26
1843 |
1844 | console.log(Math.ceil(25.3)); // 26 // Round to UpSide
1845 | console.log(Math.ceil(25.9)); // 26
1846 |
1847 | console.log(Math.floor(25.3)); // 25 // Round to DownSide
1848 | console.log(Math.floor(25.9)); // 25
1849 |
1850 | console.log(Math.trunc(-25.9)); // -25 // removed after Point
1851 | console.log(Math.floor(-25.9)); // -26 // properly rounded
1852 |
1853 | // Rounding decimals ".toFixed" returns String not Number
1854 | console.log((2.7).toFixed(0)); // "3"
1855 | console.log((2.7).toFixed(3)); // "2.700"
1856 | console.log((2.734).toFixed(4)); // "2.7340"
1857 | console.log(+(2.743).toFixed(2)); // 2.74
1858 |
1859 | // Remainder
1860 | console.log(5 % 2); // 1
1861 | console.log(5 / 2); // 2 * 2 = 4 + 1 = 5
1862 |
1863 | // Check for Even=Odd
1864 | console.log(5 % 2 === 0); // false
1865 | console.log(4 % 2 === 0); // true
1866 | ```
1867 |
1868 | #### BigInt
1869 |
1870 | ```js
1871 | // Largest Number In JS
1872 | // Total 64 bits are used to store number
1873 | // from 64 53 are used to store number other are used to store sign and decimal point of number
1874 | console.log(2 ** 53 - 1); // 9007199254740991
1875 | console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
1876 | console.log(2 ** 53 + 1); // 9007199254740992
1877 | console.log(2 ** 53 + 2); // 9007199254740994
1878 | console.log(2 ** 53 + 3); // 9007199254740996
1879 | console.log(2 ** 53 + 4); // 9007199254740996 => Not Proper Result
1880 | // To create BigInt In JS for Larger Number => Just Put "n" beside it. You good to Go...
1881 | console.log(73657836895436789405789054864637665436728n);
1882 | console.log(BigInt(43234324)); // Function to create number
1883 |
1884 | // Operation
1885 | console.log(2000n + 1234n); // 3234n
1886 | console.log(3124235542353452345n * 43768342656784435n); // 136742611758230662608192758710250075n
1887 |
1888 | const huge = 1783124987173656782350871n;
1889 | const num = 29;
1890 | // console.log(huge * num); Not Posible :: You can't add normal and BigInt Number
1891 | console.log(huge * BigInt(num)); // 51710624628036046688175259n
1892 |
1893 | // Exception
1894 | // Math.sqrt(16n); :: No Math fun Can applicable
1895 | console.log(20n > 10); // true
1896 | console.log(20n > 30); // false
1897 | console.log(20n === 20); // false
1898 | console.log(typeof 20n); // bigint
1899 | console.log(20n === '20'); // false
1900 |
1901 | console.log(huge + ' is REALLY BIG !!!'); // 1783124987173656782350871 is REALLY BIG !!! script.js:400:9
1902 |
1903 | // Division
1904 | console.log(11n / 3n); // 3n => Removes number after decimal
1905 | console.log(11 / 3); // 3.6666666666666665
1906 | ```
1907 |
1908 | #### Date
1909 |
1910 | ```js
1911 | // Create a Date
1912 | const now = new Date();
1913 | console.log(now); // Date Fri Feb 25 2022 19:16:01 GMT+0530 (India Standard Time)
1914 |
1915 | console.log(new Date('Fri Feb 25 2022 19:15:50')); // Date Fri Feb 25 2022 19:15:50 GMT+0530 (India Standard Time)
1916 | console.log(new Date('DEcember 24, 2015')); // Date Thu Dec 24 2015 00:00:00 GMT+0530 (India Standard Time)
1917 |
1918 | console.log(new Date(account1.movementsDates[0])); // Date Fri Nov 01 2019 18:45:33 GMT+0530 (India Standard Time)
1919 |
1920 | console.log(new Date(2037, 10, 19, 15, 23, 5)); // Date Thu Nov 19 2037 15:23:05 GMT+0530 (India Standard Time)
1921 | console.log(new Date(2037, 10, 33)); // Date Tue Nov 19 2019 03:01:17 GMT+0530 (India Standard Time)
1922 | console.log(new Date(0)); // Unix Time // Date Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
1923 | console.log(new Date(3 * 24 * 60 * 60 * 1000)); // 3 days after unix time // Date Sun Jan 04 1970 05:30:00 GMT+0530 (India Standard Time)
1924 |
1925 | const future = new Date(2037, 10, 19, 15, 23);
1926 | console.log(future); // Date Thu Nov 19 2037 15:23:00 GMT+0530 (India Standard Time)
1927 | console.log(future.getFullYear()); // 2037 -> full year
1928 | console.log(future.getMonth()); // 10 -> Month 0 based -> Jan - 0
1929 | console.log(future.getDate()); // 19 -> Date
1930 | console.log(future.getDay()); // 4 -> Day of the week
1931 | console.log(future.getHours()); // 15
1932 | console.log(future.getMinutes()); // 23
1933 | console.log(future.getSeconds()); // 0
1934 |
1935 | console.log(future.toISOString()); // -> 2037-11-19T09:53:00.000Z -> Universal time string
1936 | console.log(future.getTime()); // 2142237180000 -> milisecond passed till now
1937 |
1938 | console.log(new Date(2142237180000)); // milisecond to know the time
1939 |
1940 | console.log(Date.now()); // current time
1941 |
1942 | future.setFullYear(2040); // Set the new year
1943 | future.setMonth(12);
1944 | future.setDate(11);
1945 | future.setHours(2);
1946 | future.setMinutes(45);
1947 | future.setSeconds(0);
1948 |
1949 | console.log(future); // Fri Jan 11 2041 02:45:00 GMT+0530 (India Standard Time)
1950 |
1951 | // Operation On date
1952 | const future = new Date(2037, 10, 19, 15, 23);
1953 | console.log(+future); // 2142237180000 -> Total milisecond
1954 |
1955 | const calcDaysPassed = (date1, date2) =>
1956 | Math.round(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));
1957 |
1958 | const days1 = calcDaysPassed(new Date(2037, 10, 14), new Date(2037, 10, 20));
1959 | console.log(days1); // 6
1960 | ```
1961 |
1962 | #### Intl NameSpace
1963 |
1964 | Internationalization API - To convert your Data international like Dates, NUmbers, Plural Rules,etc Full read [MDN - Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)
1965 |
1966 | ```js
1967 | const now = new Date();
1968 | const locale = navigator.language; // "en-US" // Your Browser Language
1969 | console.log(
1970 | new Intl.DateTimeFormat(locale, {
1971 | timeStyle: 'short',
1972 | dateStyle: 'short',
1973 | }).format(now)
1974 | ); // 2/27/22, 2:47 PM
1975 | console.log(
1976 | new Intl.DateTimeFormat(locale, {
1977 | timeStyle: 'long',
1978 | dateStyle: 'long',
1979 | }).format(now)
1980 | ); // February 27, 2022 at 2:47:28 PM GMT+5:30
1981 |
1982 | const number = 123456.789;
1983 | console.log(
1984 | new Intl.NumberFormat('de-DE', {
1985 | style: 'currency',
1986 | currency: 'EUR',
1987 | }).format(number)
1988 | );
1989 | // expected output: "123.456,79 €"
1990 |
1991 | // the Japanese yen doesn't use a minor unit
1992 | console.log(
1993 | new Intl.NumberFormat('ja-JP', {
1994 | style: 'currency',
1995 | currency: 'JPY',
1996 | }).format(number)
1997 | );
1998 | // expected output: "¥123,457"
1999 |
2000 | // limit to three significant digits
2001 | console.log(
2002 | new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(
2003 | number
2004 | )
2005 | );
2006 | // expected output: "1,23,000"
2007 |
2008 | let amount = 3500;
2009 | new Intl.NumberFormat('en-US', { style: 'decimal' }).format(amount);
2010 | // → '3,500'
2011 | new Intl.NumberFormat('en-US', { style: 'percent' }).format(amount);
2012 | // → '350,000%'
2013 | ```
2014 |
2015 | ## Loops
2016 |
2017 | ### For Loops
2018 |
2019 | ```js
2020 | for (let rep = 0; rep <= 10; rep++) {
2021 | console.log(`Hello World ${rep}`);
2022 | }
2023 | /* output => Hello World 0
2024 | Hello World 1
2025 | Hello World 2
2026 | ...
2027 | ...
2028 | Hello World 10 */
2029 |
2030 | // Looping through Array
2031 | const chandraPrakash = [
2032 | 'ChandraPrakah',
2033 | 'Darji',
2034 | 2022 - 2002,
2035 | 'Student',
2036 | ['JavaScript', 'Python', 'Html', 'CSS'],
2037 | ];
2038 | const type = [];
2039 | for (let index = 0; index < chandraPrakash.length; index++) {
2040 | // reading
2041 | console.log(chandraPrakash[index]);
2042 | // filling the array
2043 | type[index] = typeof chandraPrakash[index];
2044 | }
2045 |
2046 | // Backword Loop
2047 | for (let index = chandraPrakash.length - 1; index >= 0; index--) {
2048 | console.log(chandraPrakash[index]);
2049 | }
2050 | /* output -> ['JavaScript', 'Python', 'Html', 'CSS']
2051 | Student
2052 | 20
2053 | Darji
2054 | ChandraPrakah */
2055 | ```
2056 |
2057 | ### For of loops
2058 |
2059 | ```js
2060 | // for of loop [ Looping The ARRAYS ]
2061 | const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
2062 |
2063 | for (const item of menu) console.log(item); // Take items one by one
2064 |
2065 | for (const item of menu.entries()) console.log(item);
2066 | /* Output ::: [0, 'Focaccia']
2067 | [1, 'Bruschetta']
2068 | [2, 'Garlic Bread']
2069 | ...
2070 | */
2071 | for (const [i, el] of menu.entries()) console.log(`${i}: ${el}`);
2072 | /* Output ::: 0: Focaccia
2073 | 1: Bruschetta
2074 | 2: Garlic Bread
2075 | ...
2076 | */
2077 |
2078 | console.log(...menu.entries()); // [0, 'Focaccia'] [1, 'Bruschetta'] [2, 'Garlic Bread'] [3, 'Caprese Salad']
2079 | // [4, 'Pizza'] [5, 'Pasta']0: 51: "Pasta"length: 2[[Prototype]]: Array(0) [6, 'Risotto']
2080 | ```
2081 |
2082 | ### ForEach loops
2083 |
2084 | In ForEach callback function the the first argument is the element and second on is index of that element, third argument in callBack is arr that is forEach loop is runned.
2085 |
2086 | ```js
2087 | // '---- 6. forEach Method ( ARRAY )----'
2088 | const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];
2089 | movements.forEach((movement, transferNo) => {
2090 | let type = movement > 0 ? 'Deposited' : 'Withdraw';
2091 | console.log(
2092 | `You ${type} ${Math.abs(
2093 | movement
2094 | )}. Your Transaction Number is ${transferNo}`
2095 | );
2096 | });
2097 |
2098 | /* Output ::: You Deposited 200. Your Transaction Number is 0
2099 | You Deposited 450. Your Transaction Number is 1
2100 | You Withdraw 400. Your Transaction Number is 2
2101 | ...
2102 | */
2103 |
2104 | // '---- 7. forEach Method ( MAP ) ----'
2105 | const currencies = new Map([
2106 | ['USD', 'United States dollar'],
2107 | ['EUR', 'Euro'],
2108 | ['GBP', 'Pound sterling'],
2109 | ]);
2110 | currencies.forEach((value, key, map) => console.log(`${key}: ${value}`));
2111 | /* Output ::: USD: United States dollar
2112 | EUR: Euro
2113 | GBP: Pound sterling
2114 | */
2115 |
2116 | // '---- 8. forEach Method ( SET ) ----'
2117 | const currenciesUnque = new Set(['USD', 'GBP', 'USD', 'EUR', 'EUR']);
2118 |
2119 | currenciesUnque.forEach((value, _, set) => console.log(value));
2120 | ```
2121 |
2122 | ### Nested Loops
2123 |
2124 | ```js
2125 | for (let i = 0; i < 5; i++) {
2126 | console.log(`---------- Exersie Set No ${i} ----------`);
2127 | for (let j = 0; j < i; j++) {
2128 | console.log(`---- Exersie lift ${j}`);
2129 | }
2130 | }
2131 | ```
2132 |
2133 | ### While loop
2134 |
2135 | ```js
2136 | // while loop -> Loop that doesn't require a counter
2137 | let rep = 1;
2138 | while (rep <= 3) {
2139 | console.log(`( ${rep} )is counter`);
2140 | rep++;
2141 | }
2142 | // Loop without Counter -> If we dont know how many time loop will run
2143 | let dice = Math.trunc(Math.random() * 6);
2144 | while (dice !== 6) {
2145 | console.log(dice);
2146 | dice = Math.trunc(Math.random() * 7);
2147 | if (dice === 6) console.log('Loops is about to end');
2148 | }
2149 | ```
2150 |
2151 | ### Loop Control Statments
2152 |
2153 | #### Continue
2154 |
2155 | ```js
2156 | // Continue -> When loop gets Continue the current itreation
2157 | // is stopped and skipped to next one ...
2158 | for (let index = 0; index < chandraPrakash.length; index++) {
2159 | if (typeof chandraPrakash[index] !== 'string') continue;
2160 | console.log(chandraPrakash[index]);
2161 | }
2162 | /* Output -> ChandraPrakah
2163 | Darji
2164 | Student*/
2165 | ```
2166 |
2167 | #### Break
2168 |
2169 | ```js
2170 | // Break -> When loop gets Break the whole is breaked
2171 | // and all itreation will not happen
2172 | for (let index = 0; index < chandraPrakash.length; index++) {
2173 | if (typeof chandraPrakash[index] === 'number') break;
2174 | console.log(chandraPrakash[index]); // no item will print if number is found
2175 | }
2176 | /* Output -> ChandraPrakah
2177 | Darji*/
2178 | ```
2179 |
2180 | ## Timers
2181 |
2182 | ### SetTimeout
2183 |
2184 | ```js
2185 | const ingredient = ['olives', 'spinach'];
2186 | // 1st argument 1 callback // 2nd time // 3rd argument for call back Fun()
2187 | const pizzaTower = setTimeout(
2188 | (ing1, ing2) => {
2189 | console.log(`Here is Pizza with ${ing1} and ${ing2} 🍕`);
2190 | },
2191 | 3000,
2192 | ...ingredient
2193 | );
2194 | console.log('Waiting...');
2195 | // Clear the timeout at specific condition
2196 | if (ingredient.includes('spinach')) clearTimeout(pizzaTower);
2197 | ```
2198 |
2199 | ### setInterval
2200 |
2201 | ```js
2202 | // Runs the call back fun() every given time
2203 | setInterval(() => {
2204 | console.log(
2205 | new Intl.DateTimeFormat('hi-IN', { timeStyle: 'long' }).format(
2206 | new Date()
2207 | )
2208 | );
2209 | }, 1000);
2210 | ```
2211 |
2212 | ## DOM Manuplication
2213 |
2214 | **Document Object Model** Structured Representation Of Html Documents. Allows Javascript To Access Html Elements And Styles To Manipulate Them.
2215 |
2216 | DOM tree Structure
2217 |
2218 | 
2219 | DOM is not Part of JavaScript ...
2220 | Javscript interact with DOM by WEB API's that browser Implements ...
2221 |
2222 | - [Accessing Dom Elements](#accessing-dom-elements)
2223 | - [Grab Children/Parent Node(s)](#grab-childrenparent-nodes)
2224 | - [Create New DOM Elements](#create-new-dom-elements)
2225 | - [Add Elements to the DOM](#add-elements-to-the-dom)
2226 | - [Remove Html Element](#remove-html-element)
2227 | - [Add/Remove/Toggle/Check Classes](#addremovetogglecheck-classes)
2228 | - [Updating Styles Using Dom](#updating-styles-using-dom)
2229 | - [Changing the Atributes](#changing-the-atributes)
2230 |
2231 | ### Accessing Dom Elements
2232 |
2233 | ```js
2234 | // Returns a reference to the element by its ID.
2235 | document.getElementById('someid');
2236 |
2237 | // Returns an array-like object of all child elements which have all of the given class names.
2238 | document.getElementsByClassName('someclass');
2239 |
2240 | // Returns an HTMLCollection of elements with the given tag name.
2241 | document.getElementsByTagName('LI');
2242 |
2243 | // Returns the first element within the document that matches the specified group of selectors.
2244 | document.querySelector('.someclass');
2245 |
2246 | // Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes)
2247 | // that match the specified group of selectors.
2248 | document.querySelectorAll('div.note, div.alert');
2249 | ```
2250 |
2251 | ### Dom traversing
2252 |
2253 | ```javascript
2254 | const h1 = document.querySelector('h1');
2255 | ```
2256 |
2257 | Going DOWNWARDS : CHILD
2258 |
2259 | ```js
2260 | // return list of node with class ".highlight"
2261 | console.log(h1.querySelectorAll('.highlight'));
2262 | // reurns list of all the child node -> text,comment,element,etc.
2263 | console.log(h1.childNodes);
2264 | // returns the html collection of element
2265 | console.log(h1.children);
2266 | ```
2267 |
2268 | Going UPWARADS : PARENT
2269 |
2270 | ```js
2271 | h1.closest('.header'); // returns the closet parent element -> can go as high it can go
2272 |
2273 | console.log(h1.parentNode);
2274 | console.log(h1.parentElement);
2275 |
2276 | // parentElement it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.
2277 |
2278 | document.body.parentNode; // the element
2279 | document.body.parentElement; // the element
2280 |
2281 | document.documentElement.parentNode; // the document node
2282 | document.documentElement.parentElement; // null
2283 |
2284 | document.documentElement.parentNode === document; // true
2285 | document.documentElement.parentElement === document; // false
2286 | ```
2287 |
2288 | Since the `` element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)
2289 | [source StackOverflow](https://stackoverflow.com/questions/8685739/difference-between-dom-parentnode-and-parentelement)
2290 |
2291 | ```js
2292 | // Going SIDEWAY : Siblings
2293 | console.log(h1.previousElementSibling); // element before h1
2294 | console.log(h1.nextElementSibling); // element after
2295 |
2296 | console.log(h1.previousSibling); // previos node
2297 | console.log(h1.nextSibling);
2298 |
2299 | console.log(h1.parentElement.children); // all siblings
2300 | ```
2301 |
2302 | ### Create New DOM Elements
2303 |
2304 | ```javascript
2305 | // create new elments
2306 | var newHeading = document.createElement('h1');
2307 | var newParagraph = document.createElement('p');
2308 |
2309 | // create text nodes for new elements
2310 | var h1Text = document.createTextNode('This is a nice header text!');
2311 | var pText = document.createTextNode('This is a nice paragraph text!');
2312 |
2313 | // attach new text nodes to new elements
2314 | newHeading.appendChild(h1Text);
2315 | newParagraph.appendChild(pText);
2316 |
2317 | // elements are now created and ready to be added to the DOM.
2318 | ```
2319 |
2320 | ### Add Elements to the DOM
2321 |
2322 | ```javascript
2323 | // grab element on page you want to add stuff to
2324 | var firstHeading = document.getElementById('firstHeading');
2325 |
2326 | // add both new elements to the page as children to the element we stored in firstHeading.
2327 | firstHeading.appendChild(newHeading);
2328 | firstHeading.appendChild(newParagraph);
2329 |
2330 | // can also insert before like so
2331 |
2332 | // get parent node of firstHeading
2333 | var parent = firstHeading.parentNode;
2334 |
2335 | // insert newHeading before FirstHeading
2336 | parent.insertBefore(newHeading, firstHeading);
2337 |
2338 | // directly add before and after
2339 | const header = document.querySelector('.header');
2340 | header.after(message);
2341 | header.before(message);
2342 | ```
2343 |
2344 | Suppose you have the following HTML:
2345 |
2346 | ```html
2347 |
Some example text
2349 |Some example text
2352 |This gets inserted.