29 |
30 | ## Primitive Data types
31 | every language out there has a group of types.
32 | Different categories for data.
33 |
Number - its a numeric value
34 |
String - text words, could be a number but inside quotation marks
35 |
Boolean - true or false values
36 |
Null
37 |
Undefined
38 |
technically there are two others- Symbol and BigInt
39 |
40 | ## Numbers in JS
41 | JS has one number type
42 |
positive numbers
43 |
negative numbers
44 |
whole number (integers)
45 |
Decimal Numbers(floats)
46 |
47 | > clear() - clears the console
48 |
49 | with numbers we have different mathematical operations that we can use kind of like a calculator.
50 |
51 | > Addition 13+15
52 |
53 | > Substraction 15-2
54 |
55 | > Multiply 12*3
56 |
57 | > Divide 12/6
58 |
59 | > Modulo 12%4 - returns the remainder
60 |
61 | > // Comments after these two forward slashes
62 |
63 |
64 | #### exponent or exponential operator
65 | which looks like this two star star.
66 | > 4 ** 2 = 16
67 |
68 | ### NAN Not a Number
69 | NaN is a numeric value that represents something that is not a number.
70 | > 0/0 = NaN
71 |
72 | > 122 + NaN = NaN
73 |
74 | It doesn't necessarily mean something went wrong.
75 |
76 |
77 | ### Infinity
78 | which we can generate by doing something like
79 | 1 divided by zero javascript just has a way of representing a value of infinity.
80 | > 1/0 = infinity
81 |
82 |
83 |
84 |
85 | # Variables
86 |
87 | Variables are like "labeled jars" for a value in JavaScript.
88 |
89 | We can store a value and give it a name, so that we can--
90 |
91 |
Recall it
92 |
Use it
93 |
Or change it later on
94 |
95 | the basic syntax that we'll see first is using a keyword called let.
96 | ```javascript
97 | let age = 14;
98 | ```
99 | Now there actually are two different ways that we can create variables in JavaScript at least two that
100 | are commonly used today.
101 |
102 | how to update a variable
103 | ```javascript
104 | age = age +1;
105 | ```
106 | we should always keep our variable names in camel case like this
107 | ```js
108 | let ageOfTushar = 20;
109 | ```
110 | ## Unary operators
111 | unary operators are operators where there's only one side.
112 | ```js
113 | let counter = 1;
114 | counter++;
115 | ```
116 |
117 | ## Const
118 | const is just like let except we can't change the value.
119 |
120 | ## legacy of var
121 | before let and const , var was only way to declare the variables. Now there's no reason to use it.
122 |
123 | lets talk about other primitive data types-
124 |
Booleans
125 | booleans are simply true or false values.
126 |
127 | ```js
128 | let isFriend = true;
129 | isFriend = false;
130 | ```
131 |
132 | -- in javascript we can change type of variables.
133 | if you have experience with any other programming language well maybe not any other but many other
134 | languages.
135 | When you declare a variable and you make it a number it needs to stay a number in JavaScript there is
136 | no restriction on that.
137 | We can change a number to a Boolean at any point.
138 |
139 | That's not saying it's a good idea at all.
140 | In fact it's one of the things a lot of people don't like about JavaScript and it's why things like
141 | TypeScript exist.
142 |
143 | # Strings
144 | strings are pieces of text, or strings of characters.We wrap them in quotes.
145 |
146 | ```js
147 | let rh = "This is going to be a good book";
148 | "hi" + 1
149 | > "hi1"
150 | "hi" - 1
151 | >NaN
152 | ```
153 |
154 | > Strings are indexed
155 | every character has a corresponding index.
156 | we can check length of a string using:
157 | ```js
158 | let s = "Tushar"
159 | let lengthOfs = s.length
160 | // accessing individual characters of a string using it's index
161 | console.log(s[0])
162 | // access last character of a string
163 | console.log(s[s.length - 1])
164 | // change characters
165 | s[1] = "u"
166 | // we can't change strings individual characters this way
167 | ```
168 | > strings are immutable in javascript
169 |
170 | ## String methods
171 | strings come with a set of built in methods. which are actions that can be performed on or with that particular string.
172 | ```js
173 | thing.method()
174 | ```
175 |
176 | ### toUpperCase()
177 | ```js
178 | let s = "tushar";
179 | s.toUpperCase(); // returns new string with UPPER case
180 | ```
181 |
182 | ### toLowerCase()
183 | ```js
184 | s.toLowerCase();// returns new string with all lowercase characters
185 | ```
186 |
187 | ### trim()
188 | It just removes trailing leading and trailing whitespace so spaces at the beginning and
189 | end of a string when you call trim it returns a string where that space has been removed.
190 | ```js
191 | s.trim()
192 | ```
193 |
194 | ## Methods with arguments
195 | some methods accepts arguments that modify their behaviour.
196 | ```js
197 | thing.method(args)
198 | ```
199 |
200 | ### indexOf()
201 | tell you where in a string a given string occurs substring.
202 |
203 | ```js
204 | let st = "Tushar Rajpoot";
205 | st.indexOf("u") // returns the index
206 | st.indexof("www") // return -1 not found
207 | ```
208 |
209 | ### slice()
210 | takes index and gives sliced string
211 | ```js
212 | let s = "Tushar";
213 | s.slice(0,3);
214 | >"Tus"
215 | ```
216 |
217 | ### replace()
218 | returns a new string with replaced substring
219 | ```js
220 | let as = "I'm Tushar and I'm a programmer";
221 | as.replace("programmer","developer")
222 | >"I'm Tushar and I'm a developer"
223 | ```
224 |
225 | ## String espace characters
226 |
227 |
\n - newline
228 |
\' - single quote
229 |
\" - double quote
230 |
\\ - backslash
231 |
232 | ## String template literals
233 | template literals are strings that allow embedded expressions, which will be evaluated and then turned into a resulting string.
234 |
235 | use backtick for string template literals
236 |
237 | ```js
238 | let tu = 13;
239 | let s = `Number of tushar- ${tu}`
240 | ```
241 |
242 | # Null and Undefined
243 | ### Null
244 | Intentional absence of any value. Must be assigned.
245 |
246 | ### Undefined
247 | Variables that don't have an assigned value are undefined.
248 |
249 | ```js
250 | let logg = null;
251 | ```
252 |
253 | # Math object
254 | contains properties and methods for mathematical constantss and functions.
255 |
256 | ```js
257 | Math.PI // 3.14...
258 |
259 | //Rounding a number
260 | Math.round(4.9) // 5
261 |
262 | // Absolute value
263 | Math.abs(-456) // 456
264 |
265 | // Raises 2 to 5th power
266 | Math.pow(2,5) // 32
267 |
268 | // Removes decimal
269 | Math.floor(3.23) // 3
270 | ```
271 |
272 | ## Random numbers
273 | Math.random() gives us a random decimal between 0 and 1 (non- inclusive)
274 |
275 | ```js
276 | Math.random() // it will return random decimal number between 0 and 1
277 | // 0.33493
278 |
279 | // genrate random number between 1 to 10
280 | const step1 = Math.random();
281 | const step2 = step1 * 10;
282 | const step3 = Math.floor(step2);
283 | const step4 = step3 +1;
284 |
285 | // so basically we can do like this
286 | Math.floor(Math.random() * 10)+1;
287 |
288 | ```
289 |
290 | ## TYPE OF
291 | we use type of to determine type of a given value.
292 |
293 | ```js
294 | let s = "tus";
295 | typeof(s)// return string
296 | // we can use without these parentheses also
297 | typeof tu
298 | ```
299 |
300 | # parseInt and parseFloat
301 | use to parse strings into numbers, but watch out for NaN.
302 | ```js
303 | let str = "123"
304 | parseInt(str)
305 | >123
306 | let s = "1.2"
307 | parseFloar(s);
308 | >1.2
309 | let st = "w1"
310 | parseInt(st);
311 | >NaN
312 | ```
313 |
314 |
315 |
316 |
317 |
How code is executed in JavaScript
318 |
Execution Context
319 | Everything in JavaScript happens inside an execution context.
320 | Assume it like a big box or container in which JS code is executed.
321 | Execution context is a wrapper around your existing code; which contains code that you have not written, but is generated by JS engine.
322 | A JavaScript execution context is created each time when you run your JS code file.
323 |
324 |
325 |
326 |
Memory Component
327 |
Code Component
328 |
329 |
330 |
Memory allocation of variables
331 |
Code execution
332 |
333 |
334 |
335 |
Components of execution context
336 |
Memory Component
337 | Memory component is a place where all the variables and keywords are stored as key value pairs.
338 | Ex: We have a variable called a equivalent to 10.
339 |
340 |
const a = 10;
341 |
342 |
343 |
344 |
345 |
Memory Component
346 |
Code Component
347 |
348 |
349 |
a:10
350 |
Code execution
351 |
352 |
353 |
354 |
Code Component
355 | This is the place where code executed one line at a time.
356 |
357 |
JavaScript is a synchronous single threaded language.
358 |
Single Threaded
359 | JavaScript can only execute one command at a time.
360 |
Synchronous Single threaded
361 | JavaScript can only execute one command at a time and in a specific order. It can only go to the next line once the current line has been finished executing.
362 |
363 |
What happens when you run your JS code
364 |
365 |
When we run a JS program, An execution context will be created
366 |
367 |
An execution context is created in two phases.
368 |
369 |
Memory creation phase
370 | In this phase JS will allocate memory to all the variables and functions.
371 |
Code execution phase
372 | In this phase, Code will be executed after it's memory allocation.
373 |
374 |
375 |
376 |
377 | Let's Assume we're executing below code
378 |
379 | ```JS
380 | var n = 2;
381 | function square(num){
382 | var ans = num*num;
383 | return ans;
384 | }
385 |
386 | var square2 = square(n)
387 | var square3 = square(3)
388 |
389 | ```
390 |
391 | So as we know first phase is creation-
392 |
Memory Allocation Phase
393 |
394 |
Allocate memory to n variable
395 |
Allocate memory to square function
396 |
397 | So when JS allocates memory what does it stores?
398 | It stores a special value known as undefined.
399 | But in case of functions, it litterally stores the whole code of the function inside the memory space.
400 |
Now JS once again runs through this whole JavaScript program line by line and it executes the code now.
418 |
This is the point when all these variables, functions, every calculation in the program is done
419 |
As soon as it counters the first line-
420 | var n = 2; It actually places the 2 insides then, till now the value of n was undefined now in the second phase of creation of execution context that is the code execution phase in this phase, this 2 value overhere of n is now been placed actually in this placeholder or the identifier which is n.
421 |
422 |
423 | On line 2 to 5 (function) it sees that here is nothing to execute so it moves to the next line.
424 |
425 |
426 | In line 6 we are invoking the function.
427 |
functions are like a mini program in JavaScript, whenever a function is invoked, a mini program is invoked so all together a new execution context is created
428 |
429 |
Whole thing, we were running this whole program was inside the global execution context, now when we run the funtion or when we invoke a function. A brand new context is created.
470 |
471 | ## Comparison Operators
472 | ```js
473 | > // greater than
474 | < // less than
475 | >= // greater than or equal to
476 | <= // less than or equal to
477 | == // equality
478 | != // not equal
479 | === // strict equality
480 | !== // strict non-equality
481 | // these give booleans true or false like this
482 | 5>2 // true
483 | 5<3 //false
484 | ```
485 |
486 | ### double equals(==)
487 |
Checks for equality of value, but not equality of type.
488 |
It coerces both values to the same type and then compares them.
489 |
This can lead to some unexpected results.
490 |
491 | ### Triple equals(===)
492 |
Checks for equality of value and type.
493 |
494 | ```js
495 | 7 == '7' // true
496 | 7 ==='7' //false
497 | ```
498 |
499 | > Always go with triple equals.
500 |
501 | ## Making decisions in the code
502 | A conditional statement can have three pieces-
503 |
If
504 |
Else if
505 |
Else
506 |
507 | ### If
508 | Run code if a given condition is true.
509 | ```js
510 | let rate = 3;
511 | if(rate===3){
512 | console.log("Amazing");
513 | }
514 | ```
515 |
516 | ### Else If
517 | if not the first thing, maybe this another thing?
518 | ```js
519 | let rate = 2;
520 | if(rate===3){
521 | console.log("Amazing");
522 | }
523 | else if(rate === 2){
524 | console.log("Oh its ok");
525 | }
526 | ```
527 |
528 | ### Else
529 | if nothing else was true, do this..
530 | ```js
531 | let rate = 349;
532 | if(rate===3){
533 | console.log("Amazing");
534 | }
535 | else if(rate === 2){
536 | console.log("Oh its ok");
537 | }
538 | else{
539 | console.log("Ok we don't know about it")
540 | }
541 | ```
542 |
543 | ### Nesting
544 | we can nest conditionals inside conditionals
545 | ```js
546 | let password = "hello kiry";
547 | if(password.length >=6){
548 | if(password.indexOf(' ')!== -1){
549 | console.log("Password can't include spaces");
550 | }
551 | else{
552 | console.log("Valid password")
553 | }
554 | }
555 | else{
556 | console.log("password is too short");
557 | }
558 | ```
559 |
560 | ## Truthy and Falsy values
561 |
All values have an inherent truthy or falsy boolean value
562 |
NOT(!)
569 |
570 | ### AND(&&)
571 | Both sides must be true in order for the whole thing to be true
572 |
573 | ```js
574 | 1<=4 && 'a'==='a'; // true
575 | 9>10 && 9>=9 ; // false
576 | ```
577 |
578 | ### OR(||)
579 | If one side is true, the whole thing is true
580 |
581 | ```js
582 | // only one side needs to be true
583 | 1!==1 || 10===10 // true
584 | ```
585 |
586 | ### NOT(!)
587 | returns true if the expression is false
588 |
589 | ```js
590 | !null // true
591 |
592 | !(0===0) // false
593 | ```
594 |
595 | ## Operator precedence
596 |
NOT(!) has higher precedence than && and ||.
597 |
&& has higher precedence than ||.
598 |
599 | ```js
600 | ! && ||
601 | ```
602 | we can alter these using parentheses.
603 |
604 |
605 | ## Switch Statement
606 |
607 | The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.
608 |
609 | Syntax---
610 |
611 | ```js
612 | switch (expression) {
613 | case value1:
614 | //Statements executed when the
615 | //result of expression matches value1
616 | [break;]
617 | case value2:
618 | //Statements executed when the
619 | //result of expression matches value2
620 | [break;]
621 | ...
622 | case valueN:
623 | //Statements executed when the
624 | //result of expression matches valueN
625 | [break;]
626 | [default:
627 | //Statements executed when none of
628 | //the values match the value of the expression
629 | [break;]]
630 | }
631 | ```
632 |
633 | ## Ternary Operator
634 |
635 | ```javascript
636 | condition ? expIfTrue: expIfFalse
637 | ```
638 |
639 |
640 |
641 | ## Some questions
642 |
643 |
656 |
657 | ### Creating arrays
658 | ```js
659 | // make an empty array
660 | let students = [];
661 |
662 | // array of strings
663 | let names = ["Rahul", "Tushar", "Sahul"];
664 |
665 | // an array of numbers
666 | let rollNo = [23,45,2,34,6,7]
667 |
668 | // mixed array
669 | let stuff = [true, 435, 'tushar', null];
670 | ```
671 |
672 | #### Arrays are indexed
673 | ```js
674 | let colors = ['red','orange','yellow','green']
675 | colors.length//4
676 |
677 | colors[0] // 'red'
678 | colors[1] // 'orange'
679 | colors[2] // 'yellow'
680 | colors[3] // 'green'
681 | colors[4] // 'undefined'
682 | ```
683 | ### modifying arrays
684 | unlike strings, arrays are mutable, we can modify arrays
685 |
686 | ```js
687 | let shop = ['milk','sugar'];
688 | shop[1] = 'coffee';
689 | // add something at the end
690 | shop[shop.length] = 'tomatos'
691 | ```
692 |
693 | ## Array Methods
694 |
Push - add to end
695 |
Pop - remove from end
696 |
Shift remove from start
697 |
Unshift - add to start
698 |
________________________________________
699 |
concat - merge arrays
700 |
includes - look for a value, returns true or false
701 |
indexOf - just like str.indexOf
702 |
join - creates a string from arr
703 |
reverse - reverses an array
704 |
slice - copy portion of an arr
705 |
splice - remove/replace elements
706 |
sort - sorts an array.
707 | The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
708 |
709 | >arrays are reference types which means that the actual array data is not the content that is stored in the slot in memory for each variable.Instead it is a reference.
710 |
711 | >we can modify array elements even it's initialized by const.
712 |
713 |
Objects in JavaScript
714 |
715 | An object allows us to store data where we can associate things in group pieces of data together but rather than simply ordering data based off of an index to zero with item the first the second like an array does.
716 |
717 |
Objects are collections of properties.
718 |
Properties are a key value pair.
719 |
Rather than accessing data using an index, we use custom keys.
720 | Property- key+ value
721 |
722 |
723 | ```js
724 | const student = {
725 | name: "Tushar",
726 | rollno: 123,
727 | class: 12
728 | }
729 | ```
730 |
731 | in other languages like Python objects are actually
732 | called dictionaries.
733 |
734 | ## Creating objects literals
735 | Instead of the square braces that we use for an array we use curly braces to signify an object.
736 |
737 | ```js
738 | // accessing properties
739 | student.name // accessing name
740 | ```
741 |
742 | >when we create an object when we make a property the keys are automatically converted to strings.
743 |
744 | ```js
745 | let num ={
746 | 34: "thirty four"
747 | }
748 | num.34 // throw error because it has converted to a string
749 | ```
750 |
751 | ### Accessing objects properties
752 | ```js
753 | const colors ={
754 | red: "#eb4d4b",
755 | yellow: "#f9ca24",
756 | blue: "#30336b"
757 | }
758 | colors.red
759 | colors['blue']
760 | let cr = 'yellow';
761 | colors[cr]
762 |
763 | const numbers = {
764 | 100: 'one hundred',
765 | 16: 'sixteen'
766 | '34 thing': "good"
767 | };
768 | numbers[100] // 'one hundred'
769 | numbers['34 thing']
770 | ```
771 |
772 | ### Adding and updating properties
773 |
774 | ```js
775 | const users={}
776 | users['facebook'] = "Tushar";
777 | users.insta = "tush_tr";
778 | ```
779 |
780 | ### Nested arrays and objects
781 | We can fill objects with keys that are arrays or also keys that are other objects. And we do this all the time because most of the data we work with in the real world is generally a combination of list or ordered data as well as key value pairs of data.
782 |
783 | ```js
784 | const shopCart = [
785 | {
786 | product: 'milk',
787 | price: 12,
788 | quantity: 1
789 | },
790 | {
791 | product: 'water bottle',
792 | price: 20,
793 | quantity: 5
794 | },
795 | {
796 | product: 'coffee',
797 | price: 2,
798 | quantity: 20
799 | }
800 | ]
801 |
802 | const student = {
803 | firstName: 'Tushar',
804 | lastName: 'Rajpoot',
805 | hobbies: ['Music', 'reading'],
806 | marks:{
807 | mid: 56,
808 | final: 94
809 | }
810 | }
811 | ```
812 |
813 | We know that values in an array are not actually stored in a variable. The variable has limited space available to it. So it stores a reference sort of an address.
814 | objects also work the exact same way.
815 |
816 | >we use const when we want the reference to stay the same like we always want to be pointing to this one object but the contents can come and go.
817 |
818 | #### Equality in arrays and objects
819 | the value of that variable has the little space in memory is not storing the array it's simply storing
820 | a reference to this array.
821 | ```js
822 | let n = [1,2,3];
823 | let r = [1,2,3];
824 | n==r // false
825 | n===r // false
826 | // so what we can do
827 | let newn = n;
828 | // now
829 | newn===n // true
830 | ```
831 | if you're trying to compare arrays if you're trying to see if an array is equal to another array it's not as straightforward as you might hope it would be because a lot of times you're not trying to check if an array is the exact same array.
832 |
833 |
Loops in JavaScript
834 | Doing things repeatedly.
835 |
836 |
837 | Loops allow us to repeat code
838 |
---Print 'hello' 10 times
839 |
---Sum all numbers in an array
840 |
841 |
842 | There are multiple types:
843 |
---For loop
844 |
---While Loop
845 |
---for....of loop
846 |
---for....in loop
847 |
848 |
849 |
850 | ## For Loops
851 |
852 | ```js
853 | for(
854 | [initialExpression];
855 | [condition];
856 | [incrementExpression];
857 | ){}
858 | // print hello 10 times--
859 | for(let i=0;i<=10;i++){
860 | console.log('hello');
861 | }
862 | ```
863 |
864 | #### print a multiplication table
865 | ```js
866 | const table = (num)=>{
867 | for(let i=0;i<=10;i++){
868 | console.log(`${num} X ${i} = ${num*i}`);
869 | }
870 | }
871 | table(4);
872 | ```
873 |
874 | ### For loops and arrays
875 | we can use for loops to iterate over a string or an array.
876 | To loop over an array, start at 0 and continue to the last index(length-1).
877 |
878 | ```js
879 | const students = ['Ram','Shyam','Mohan'];
880 | for(let i=0;i=0;i--){
886 | console.log(studentName[i]);
887 | }
888 | ```
889 |
890 | ### Nested for loops
891 | we can nest loops
892 | ```js
893 | for(let i=0;i<=10;i++){
894 | console.log("Outer loop",i);
895 | for(let j=10;j>=0;j--){
896 | console.log("Inner loop",j);
897 | }
898 | }
899 | // we can use nested loops for iterating 2d arrays
900 | const gameBoard = [
901 | [4,32,8,4],
902 | [64,8,32,2],
903 | [8,32,16,4],
904 | [2,8,4,2]
905 | ];
906 | for(let i=0;i < gameBoard.length;i++){
907 | // console.log(gameBoard[i]);
908 | for(let j=0;j ["South", "BollyWood", "Hollywood"]
988 | Object.values(movieRatings)
989 | // > [9.5, 2.5, 9.8]
990 | for(let x of Object.keys(movieRatings)){
991 | console.log(x)
992 | }
993 | for(let ratings of Object.values(movieRatings)){
994 | console.log(ratings);
995 | }
996 | ```
997 |
998 | > We can loop over the keys of an object, using Object.key() and values using Object.values()
999 |
1000 | ## For In Loop
1001 | Loop over the keys in an object
1002 | ```js
1003 | for(variable in object){
1004 | statement
1005 | }
1006 | // iterate over an object keys
1007 | const movieRatings ={South: 9.5, BollyWood: 2.5,Hollywood: 9.8};
1008 | for(let movie in movieRatings){
1009 | console.log(movie)
1010 | }
1011 | // accessing values with for in loop
1012 | for(let movie in movieRatings){
1013 | console.log(movie)
1014 | console.log(movieRatings[movie])
1015 | }
1016 | ```
1017 |
1018 |
Functions
1019 |
1020 | Reusable procedures
1021 |
Functions allow us to write reusable, modular code.
1022 |
We define a 'chunk' of code that we can then execute at a later point.
1023 |
1024 | ### Defining functions
1025 | ```js
1026 | function funcName(){
1027 | // do something
1028 | }
1029 | // let's write our first function
1030 | function hello(){
1031 | console.log("Hello")
1032 | }
1033 | ```
1034 |
1035 | ### function arguments
1036 |
1037 | we can also write functions that accept inputs, called arguments.
1038 |
1039 | ```js
1040 | function greet(person){
1041 | console.log(`hello ${person}`)
1042 | }
1043 | function add(a,b){
1044 | console.log(a+b);
1045 | }
1046 | ```
1047 |
1048 | ### Return statement
1049 | built-in methods return values when we call them. We can store those values:
1050 |
1051 | ```js
1052 | function add(x,y){
1053 | return x+y;
1054 | }
1055 | console.log(add(2,3));
1056 | // we can capture a return value in a variable.
1057 | let a = add(2,3)
1058 | ```
1059 |
1060 | #### No return
1061 | our functions print values out, but don't return anything.
1062 | ```js
1063 | function add(x,y){
1064 | console.log(x+y)
1065 | }
1066 | add(3,3);
1067 | ```
1068 |
1069 |
1070 |
1071 |
1072 |
1073 |
Other Important concepts about functions
1074 |
1075 | ### What is scope?
1076 |
1077 | > Variable "visibility"
1078 |
1079 |
The location where a variable is defined dictates where we have access to that variable.
1080 |
1081 | ### Function Scope
1082 |
1083 | ```js
1084 | function show(){
1085 | let msg = "Hey I'm here";
1086 | // msg is scoped to the show function
1087 | }
1088 | // we can't access or manipulate msg variable outside of this function.
1089 | ```
1090 |
1091 | ### Block Scope
1092 |
1093 | ```js
1094 | let rad = 8;
1095 | if(rad>0){
1096 | var a = 12;
1097 | const PI = 3.14;
1098 | let area = 2*PI*rad;
1099 | }
1100 | console.log(rad) // 8
1101 | console.log(area) // undefined
1102 | console.log(a) // 12
1103 | // this tells us that let and const have
1104 | // different scoping rules than var
1105 | // there was one more problem with var
1106 | let arr = [1,2,3,4];
1107 | for(var i=0;i Functions are objects
1138 | We can put functions in an array.
1139 | We can also put a function in an object.
1140 |
1141 | ### Functions as arguments
1142 | passing functions as an argument to another function or returning a function which is actually a very key part of javascript.
1143 |
1144 |
1145 | #### What are higher order functions?
1146 | Functions that operate on/with other functions. They can:
1147 |
Accept other functions as arguments
1148 |
Return a function
1149 |
1150 | ```js
1151 | function callTwice(func){
1152 | func();
1153 | func();
1154 | }
1155 |
1156 | function laugh(){
1157 | console.log("hahahahahhah");
1158 | }
1159 |
1160 | callTwice(laugh);
1161 | ```
1162 |
1163 | ### Returning functions
1164 | ```js
1165 | function makeBetweenFunc(min,max){
1166 | return function (val){
1167 | return val>=min && val<=max;
1168 | }
1169 | }
1170 | const inAgeRange = makeBetweenFunc(18,100);
1171 | console.log(inAgeRange(45)) // true
1172 | ```
1173 |
1174 | ## Callback Functions
1175 | A callback function is a function passed into another function as an argument, which is then invoked inside the outer function.
1176 |
1177 | ```js
1178 | function callTwice(func){
1179 | func();
1180 | func();
1181 | }
1182 | function laugh(){
1183 | console.log("hahahahha");
1184 | }
1185 | callTwice(laugh) // pass a function as argument
1186 | // so here laugh is a callback function
1187 | // we can also do the same like this
1188 | callTwice(function (){
1189 | console.log("Calling again");
1190 | })
1191 | ```
1192 |
1193 | We can write our own function that accepts callbacks but also tons of the built in methods, that are really useful ones in JavaScript expect you to pass in a callback.
1194 | if you want to make a request to load data from Facebook API. That request takes time. We pass in a callback function that will be called when the request is finished. When the data is back if we want to run code when a user clicks on a button on a page or when they hover over a photo the code that we write to set that up requires us to pass in a callback function which will be executed when the user hovers or when the user clicks.
1195 |
1196 | #### Anonymous functions
1197 | we use anonymous functions when we call callback functions(higher order functions). We pass in an anonymous function rather than an existing function like laugh.
1198 |
1199 | There's nothing wrong with this
1200 | ```js
1201 | callTwice(laugh)
1202 | ```
1203 | but sometimes we just need a one time use function. We don't need it to be a standalone function in which case we use an anonymous function.
1204 |
1205 | ### setTimeout function
1206 | There is a method called set timeout set timeout will run a certain block of code or a function of code after a certain number of milliseconds or seconds we pass in a number of milliseconds like five thousand which is five seconds but the first argument we need to pass it is a function so a function to run and then how long to wait before it runs.
1207 |
1208 | ```js
1209 | function notice(){
1210 | alert("go away");
1211 | }
1212 | setTimeout(notice,5000);
1213 | // this will wait till 5 second then execute notice function
1214 | // so we don't to define a function always we can use anonymous function like this
1215 | setTimeout(function(){
1216 | alert("Go away");
1217 | },5000);
1218 | ```
1219 |
1220 | ## Hoisting
1221 |
1222 | >Hoisting is JavaScript's default behavior of moving declarations to the top.
1223 |
1224 | Remember that variables when we declare them but don't initialize them. For example var x and I don't give it a value, X is set to undefined.
1225 | ```js
1226 | let x;
1227 | >undefined
1228 | ```
1229 |
1230 | so when you execute a js program, it hoists up all variable declaration. for ex, if you try to run this code
1231 | ```js
1232 | console.log(student); // undefined
1233 | var student = "Tushar"
1234 | ```
1235 | When javascript is interpreting the code what happens is that it hoists up I'm doing air quotes but
1236 | you can't see it. It hoist up the variable declaration.(var student)
1237 |
1238 | #### With let and const-
1239 | Variables defined with let and const are hoisted to the top of the block, but not initialized.
1240 | Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.
1241 |
1242 | Using a let variable before it is declared will result in a ReferenceError.
1243 |
1244 | >when you declare variable with let it's not hoisted.
1245 |
1246 |
1247 | Using a const variable before it is declared, is a syntax errror, so the code will simply not run.
1248 |
1249 | > Let and const are not hoisted
1250 |
1251 | #### Functions are hoisted
1252 | ```js
1253 | show();
1254 | function show(){
1255 | console.log("helooooo");
1256 | }
1257 | ```
1258 |
1259 | But But if we use function expression, it not gonna work
1260 | ```js
1261 | console.log(show) // undefined because its a variable that has been declared
1262 | show(); // error
1263 | var show = function(){
1264 | console.log("Hloooo")
1265 | }
1266 | // but if we declare this function using let or const it will not work.
1267 | ```
1268 |
1269 |
Array callback methods
1270 |
1271 |
Arrays come with many built-in methods that accept callback functions.
1272 |
1273 | ## For Each
1274 | accepts a callback function.
1275 | Calls the function once per element in the array.
1276 |
1277 | ```js
1278 | const num = [1,2,3,4,5,6];
1279 | num.forEach(function(n){ // n parameter represents one element at a time
1280 | console.log(n)
1281 | })
1282 | ```
1283 | We can also add a second parameter to our callback to the function here if we want to use the index.
1284 | ```js
1285 | num.forEach(function(e,i){
1286 | console.log(i,e);
1287 | })
1288 | ```
1289 |
1290 | ## Map Method
1291 | creates a new array with the results of calling a callback on every element in the array
1292 |
1293 | ```js
1294 | const texts = ['fer','rrer','rer','erre'];
1295 | const caps = texts.map(function(t){
1296 | return t.toUpperCase();
1297 | })
1298 | ```
1299 |
1300 | ## Arrow Functions
1301 | Syntactically compact alternative to a regular function expression.
1302 | ```js
1303 | const square = (x)=>{
1304 | return x*x;
1305 | }
1306 | ```
1307 |
1308 | ### Implicit return
1309 | all these functions do the same thing:
1310 | ```js
1311 | const isEven = function(num){
1312 | return num%2===0;
1313 | }
1314 | const isEven = (num)=>{
1315 | return num%2===0;
1316 | }
1317 | const isEven = num =>{
1318 | return num%2===0;
1319 | }
1320 | const isEven = num =>{ // implicit return
1321 | num%2===0
1322 | }
1323 | const isEven = num=> num%2===0;// one-liner implicit return
1324 | ```
1325 |
1326 | ## Find method
1327 | returns the value of the first element in the array that satisfies the provided testing function.
1328 |
1329 | ```js
1330 | let shoppingList = [
1331 | "Veggies",
1332 | "Milk",
1333 | "Notebooks"
1334 | ]
1335 | let item = shoppingList.find(item=>{
1336 | return item.includes("Milk");
1337 | })
1338 | ```
1339 |
1340 | ## Filter method
1341 | creates a new array with all elements that pass the test implemented by the provided function.
1342 | ```js
1343 | const numbers = [12,334,542,3,34,54,5,45,3,4,523,6,3]
1344 | const evens = numbers.filter(n=>{
1345 | return n%2===0;
1346 | })
1347 | ```
1348 |
1349 | ## Every and Some method
1350 | #### Every-
1351 | tests whether all elements in the array pass the provided function It returns a boolean value.
1352 | ```js
1353 | const words = ['dog','dog','dig','dag','bag'];
1354 | words.every(word=>{
1355 | return word.length === 3;
1356 | }) // true
1357 | ```
1358 |
1359 | #### Some -
1360 | Similar to every, but returns true if any of the array elements pass the test function.
1361 | ```js
1362 | words.some(word=>{
1363 | return word.length >4;
1364 | })
1365 | ```
1366 |
1367 | ## Sort
1368 |
1369 | arr.sort(compareFunc(a,b)))
1370 |
1371 |
If compareFunc(a,b) returns less than 0
1372 | -> Sort a before b
1373 |
If compareFunc(a,b) returns 0
1374 | -> leave a and b unchanged with respect to each other
1375 |
If compareFunc(a,b) returns greater than 0
1376 | -> Sort b before a
1377 |
1378 |
1379 |
1380 | ```js
1381 | const prices = [122,4542,453,5248,78709,3435];
1382 | prices.sort(); // it's weird converts into strings then sort
1383 |
1384 | prices.sort((a,b)=> a-b);
1385 |
1386 | prices.sort((a,b)=>b-a);
1387 |
1388 | ```
1389 |
1390 | ## Reduce Method
1391 | executes a reducer function on each element of the array, resulting in a single value.
1392 |
1393 | #### Summing an array
1394 | ```js
1395 | const arr = [3,5,7,9,11];
1396 | arr.reduce((accumulator, currentValue)=>{
1397 | return accumulator+currentValue;
1398 | })
1399 | ```
1400 |
1401 |
1402 |
1403 |
Callback
1404 |
Accumulator
1405 |
Currentvalue
1406 |
return value
1407 |
1408 |
1409 |
first call
1410 |
3
1411 |
5
1412 |
8
1413 |
1414 |
1415 |
second call
1416 |
8
1417 |
7
1418 |
15
1419 |
1420 |
1421 |
third call
1422 |
15
1423 |
9
1424 |
24
1425 |
1426 |
1427 |
fourth call
1428 |
24
1429 |
11
1430 |
35
1431 |
1432 |
1433 |
1434 |
1435 | it's not always about summing or multiplying or accumulating data in one number. It could be finding the maximum value in an entire array.
1436 |
1437 | #### Initial value
1438 | when you use reduce you can actually pass in an initial starting value. So after your callback the format would be something dot reduce.
1439 | ```js
1440 | [12,23,5,6].reduce((acc,curr)=>{
1441 | return acc+curr;
1442 | },100)
1443 | ```
1444 |
1445 | #### Tallying
1446 | we can tally up results from an array we can group different values in an array using an object.
1447 | ```js
1448 | const vote = ['y','y','n','y','y','y','n']
1449 | const tally = vote.reduce((tally, vote)=>{
1450 | tally[vote] = (tally[vote] || 0)+1
1451 | return tally;
1452 | },{})
1453 | // {}- initial object
1454 | ```
1455 |
1456 |
1457 | list of some important JS new features
1458 |
1459 |
1460 |
Arrow functions
1461 |
String template literals
1462 |
Let and const
1463 |
1464 |
1465 |
For...of
1466 |
for...in
1467 |
Exponent operator
1468 |
1469 |
1470 |
String.includes()
1471 |
Array.includes()
1472 |
Object.values()
1473 |
1474 |
1475 |
Rest & Spread
1476 |
Destructuring
1477 |
Default function params
1478 |
1479 |
1480 |
Object Enhancements
1481 |
Classes
1482 |
Async Functions
1483 |
1484 |
1485 | ## Default parameter
1486 | ```js
1487 | function multiply(a,b=1){
1488 | //means if no b is passed in if it's undefined. Use this value.
1489 | return a*b;
1490 | }
1491 | multiply(4); // 4
1492 | multiply(4,3); // 12
1493 | ```
1494 |
1495 | ## Spread
1496 | It does many things.
1497 |
1498 | Spread syntax allows an iterable such as an array to be expanded in places where zero or more arguments(for function calls) or elements(for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs(for object literals) are expected.
1499 |
1500 | ```js
1501 | function sum(x, y, z) {
1502 | return x + y + z;
1503 | }
1504 |
1505 | const numbers = [1, 2, 3];
1506 |
1507 | console.log(sum(...numbers));
1508 | // expected output: 6
1509 | console.log(sum.apply(null, numbers));
1510 | // expected output: 6
1511 | ```
1512 |
1513 | ### Spread in array literals
1514 | In array literals -
1515 |
1516 | Create a new array using an existing array. Spreads the elements from one array into a new array.
1517 |
1518 | ```js
1519 | const n1 = [1,2,3];
1520 | const n2 = [4,5,6];
1521 | [...n1,...n2];
1522 | // [1,2,3,4,5,6]
1523 |
1524 | ['a','b',...n2];
1525 | // ["a","b",4,5,6]
1526 |
1527 | const a = [1,2,3]
1528 | const b = [23]
1529 | b.push(...a)
1530 | console.log(b)
1531 | // [23, 1, 2, 3]
1532 | ```
1533 |
1534 | #### In object literals
1535 | copies properties from one object into another object literal.
1536 |
1537 | ```js
1538 | const dog = {name: "Joolie",age:6};
1539 | const animal = {...dog, isPet: true};
1540 | // {name: "Joolie",age:6,isPet: true}
1541 | ```
1542 |
1543 | ## The arguments object
1544 |
Available inside every function
1545 |
It's like an array-like object
1546 | Has a length property
1547 | Does not have array methods like push/pop
1548 |
Contains all the arguments passed to the function
1549 |
Not available inside of arrow functions
1550 |
1551 | ```js
1552 | function sumAll(){
1553 | let total = 0;
1554 | for(let i=0; i< arguments.length; i++){
1555 | total += arguments[i];
1556 | }
1557 | return total;
1558 | }
1559 | sumAll(8,3,4,5);
1560 | ```
1561 |
1562 | ## Rest (...) Params
1563 | collects all remaining arguments into an actual array.
1564 |
1565 | ```js
1566 | function sum(...numbers){
1567 | return nums.reduce((t,c)=>{
1568 | return t+c;
1569 | })
1570 | }
1571 | // we can use this in arrow function
1572 | const fullName = (firstName, secondName, ...titles)=>{
1573 | console.log('first',firstName)
1574 | console.log('second',secondName)
1575 | console.log('titles',titles)
1576 | }
1577 | ```
1578 |
1579 |
1580 | ## Destructuring
1581 | A short, clean syntax to 'unpack':
1582 |
values from arrays
1583 |
Properties from objects
1584 | Into distinct variables.
1585 |
1586 | ### Destructuring arrays
1587 | ```js
1588 | const arr = [223,535,536];
1589 | const [one,two,three] = arr;
1590 | one// 223
1591 | two // 535
1592 | three // 536
1593 |
1594 | const [one, ...everyElse] = arr;
1595 | one // 223
1596 | everyElse // [535,536]
1597 | ```
1598 |
1599 | ### Destructuring objects
1600 | ```js
1601 | const runner = {
1602 | first : "Eliud",
1603 | last: "Kipchoge",
1604 | country: "Kenya",
1605 | title: "Elder of the order of the golden heart of kenya"
1606 | }
1607 |
1608 | const {first, last, country} = runner;
1609 | first // "Eliud"
1610 | last // "Kipchoge"
1611 | country // "Kenya"
1612 |
1613 | const {country: nation} = runner;
1614 | nation // "Kenya"
1615 | ```
1616 |
1617 | ### Parameters destructuring
1618 | ```js
1619 | const fullName = ({first,last})=>{
1620 | return `${first} ${last}`
1621 | }
1622 | const runner = {
1623 | first : "Eliud",
1624 | last: "Kipchoge",
1625 | country: "Kenya",
1626 | title: "Elder of the order of the golden heart of kenya"
1627 | }
1628 | fullName(runner); // Eliud Kipchoge
1629 | ```
1630 |
1631 |
Object Methods and the "This" Keyword
1632 |
1633 | ### Short hand properties
1634 | ```js
1635 | const a = 12;
1636 | const t = "Tushar";
1637 | const n = {a,t};
1638 | console.log(n)
1639 | // {a: 12, t: "Tushar"}
1640 | ```
1641 |
1642 | ### Computed Properties
1643 | we can use a variable as a key name in an object literal property.
1644 | ```js
1645 | const role = 'SDE';
1646 | const person = "Tushar";
1647 | const role2 = 'Sys Admin';
1648 | const person2 = 'Navneet';
1649 |
1650 | const team = {};
1651 | team[role] = person;
1652 | team[role2] = person2;
1653 | // or
1654 | const team = {
1655 | [role]: person,
1656 | [role2]: person2,
1657 | [23+34]: 'Another'
1658 | }
1659 |
1660 | const addProp = (obj,k,v)=>{
1661 | return{
1662 | ...obj,
1663 | [k]:v
1664 | }
1665 | }
1666 | ```
1667 |
1668 | ## Methods
1669 | We can add functions as properties on objects.
1670 |
1671 | we call them methods.
1672 |
1673 | ```js
1674 | const math ={
1675 | multiply: function(x,y){
1676 | return x*y;
1677 | },
1678 | divide: function(x,y){
1679 | return x/y;
1680 | }
1681 | }
1682 | ```
1683 |
1684 | ### Method short hand syntax
1685 | we do this so often that there's a new shorthand way ofadding methods.
1686 |
1687 | ```js
1688 | const math = {
1689 | msg: "Hii this is math",
1690 | add(x,y){
1691 | return x+y;
1692 | }
1693 | multiply(x,y){
1694 | return x*y
1695 | }
1696 | }
1697 |
1698 | math.add(40,50) // 90
1699 | ```
1700 |
1701 | ## This keyword
1702 | The JavaScript this keyword refers to the object it belongs to. It has different values depending on where it is used: ... In a function, this refers to the global object.
1703 |
1704 |
1705 | It has different values depending on where it is used:
1706 |
In a method, this refers to the owner object.
1707 |
Alone, this refers to the global object.
1708 |
In a function, this refers to the global object.
1709 |
In a function, in strict mode, this is undefined.
1710 |
In an event, this refers to the element that received the event.
1711 |
Methods like call(), and apply() can refer this to any object.
1712 |
1713 | >The value of this depends on the invocation context the unction it is used in.
1714 |
1715 | ```js
1716 | const person = {
1717 | first: "Tushar",
1718 | last : "Rajpoot",
1719 | nickName: false,
1720 | fullName(){
1721 | // console.log(this)
1722 | return `${this.first} ${this.last}`
1723 | },
1724 | printBio(){
1725 | const fullName = this.fullName();
1726 | console.log(`${fullName} is a person`)
1727 | }
1728 | }
1729 | ```
1730 | > We should not use arrow functions in methods
1731 |
1732 |
1733 |
Document Object Model
1734 |
The DOM is a JavaScript representation of a webpage.
1735 |
It's your JS "window" into the contents of a webpage
1736 |
It's just a bunch of objects that you can interact with via JS.
1737 |
1738 | ### The Document Object
1739 | The document object is our entry point into the world of the DOM. It contains representations of all the content on a page, plus tons of useful methods and properties.
1740 |
1741 | ### Selecting
1742 |
1942 |
1943 | #### Responding to user inputs and actions.
1944 |
1945 |
clicks
1946 |
drags
1947 |
drops
1948 |
hovers
1949 |
scrolls
1950 |
form submission
1951 |
key presses
1952 |
focus/blur
1953 |
mouse wheel
1954 |
double click
1955 |
copying
1956 |
pasting
1957 |
audio start
1958 |
screen resize
1959 |
printing
1960 |
1961 | ## Using Events
1962 | ### using on
1963 | ```HTML
1964 |
1965 | ```
1966 | >More content will be added soon for events
1967 |
1968 |
1969 |
1970 |
1971 |
Asynchronous JavaScript, Callbacks and Promises
1972 |
1973 | ## Call Stack
1974 | The mechanism the JS interpreter uses to keep track of its place in a script that calls multiple functions.
1975 |
1976 | How JS "knows" what function is currently being run and what functions are called from within that function etc.
1977 |
1978 | ### How it works
1979 |
1980 |
When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
1981 |
1982 |
Any functions that are called by that function are added the call stack further up, and run where their callls are reached
1983 |
1984 |
When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off the last code listing.
1985 |
1986 | >Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). There are many real-life examples of a stack
1987 |
1988 | ```js
1989 | const multiply = (x,y) => x*y;
1990 | const square = (x) => multiply(x,x);
1991 |
1992 | const isRightTriangle = (a,b,c)=>{
1993 | return square(a) + square(b)=== square(c);
1994 | }
1995 |
1996 | isRightTriangle(3,4,5);
1997 | // square(3) + square(4)===square(4)
1998 |
1999 | ```
2000 |
2001 | ## JavaScript is a single threaded language
2002 | At any given point in time, that single JS thread is running at most one line of JS code.
2003 |
2004 |
2005 | ## How asynchronous callbacks actually work?
2006 |
2007 |
Browsers come with web APIs that are able to handle certain tasks in the background (like making requests or setTimeout)
2008 |
The JS call stack regocnizes these web API functions and passes them off to the browser to take care of
2009 |
Once the browser finishes those tasks, they return and are pushed onto the stack as a callback.
2010 |
2011 | try your code here :- click here
2012 |
2013 |
2014 | ## Callback Hell
2015 |
2016 | ### What is Synchronous Javascript?
2017 | In Synchronous Javascript, when we run the code, the result is returned as soon as the browser can do. Only one operation can happen at a time because it is single-threaded. So, all other processes are put on hold while an operation is executing.
2018 |
2019 | ### What is Asynchronous Javascript?
2020 |
2021 |
Some functions in Javascript requires AJAX because the response from some functions are not immediate. It takes some time and the next operation cannot start immediately. It has to wait for the function to finish in the background. In such cases, the callbacks need to be asynchronous.
2022 |
There are some external Javascript Web APIs that allows AJAX – Asynchronous Javascript and XML.
2023 | In AJAX, many operations can be performed simultaneously.
2024 |
2025 | ### What is a callback?
2026 |
2027 |
Callbacks are nothing but functions that take some time to produce a result.
2028 |
Usually these async callbacks (async short for asynchronous) are used for accessing values from databases, downloading images, reading files etc.
2029 |
As these take time to finish, we can neither proceed to next line because it might throw an error saying unavailable nor we can pause our program.
2030 |
So we need to store the result and call back when it is complete.
2031 |
2032 | ### What is callback hell?
2033 | This is a big issue caused by coding with complex nested callbacks. Here, each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected.
2034 |
2035 | # Promises
2036 | A promise is an object representing the eventual completion or failure of an asynchronous operation.
2037 |
2038 | > A Pattren for writing async code.
2039 |
2040 | A promise is a returned object to which we can attach callbacks, instead of passing callbacks into a function.
2041 |
2042 | when we create a promise, we pass in a function. And this function has two parameters. Always these two parameters we usually call resolve and reject. And these are actually functions.
2043 |
2044 | Inside of inside promise function if we call resolve, the promise will be resolved. If we call reject, the promise will be rejected.
2045 |
2046 |
If we don't resolve or reject it, it's status will be pending.
2047 |
If we reject it, our promise status will be rejected.
2048 |
If we resolve it, promise status will be resolved.
2049 |
2050 |
2051 |
2052 | ```js
2053 | // create a promise which resolved using a random number
2054 | const getMePhone = new Promise((resolve,reject) => {
2055 | let rand = Math.random()
2056 | if(rand<0.5){
2057 | resolve()
2058 | }
2059 | else{
2060 | reject()
2061 | }
2062 |
2063 | })
2064 | ```
2065 |
2066 | #### How do I run code if this promise was rejected versus run code, if this promise was resolved?
2067 | .then: every promise has a then method. this then method will run if our promise is resolved.
2068 |
2069 | .catch Every promise has a catch method also. We can chain it with .then or we can write along with promise.
2070 |
2071 | ```js
2072 | getMePhone.then(()=>{
2073 | console.log("Yeah I got a Phone")
2074 | }).catch(()=>{
2075 | console.log("No Phone")
2076 | })
2077 | ```
2078 |
2079 |
2080 |
2081 | ## Returning promises from Functions
2082 |
2083 | ```js
2084 | // returning a promise from a function
2085 | const makeDogPromise = () => {
2086 | return new Promise((resolve, reject) => {
2087 | setTimeout(() => {
2088 | const rand = Math.random();
2089 | if (rand < 0.5) {
2090 | resolve()
2091 | }
2092 | else
2093 | reject()
2094 | }, 5000)
2095 | })
2096 | }
2097 | makeDogPromise().then(()=>{
2098 | console.log("hello")
2099 | })
2100 | ```
2101 |
2102 | ## Resolving/rejecting promises with values
2103 | we can pass information in to the resolve or reject calls.
2104 | ```js
2105 | const fakeRequest = (url)=>{
2106 | return new Promise((resolve,reject)=>{
2107 | setTimeout(()=>{
2108 | const pages = {
2109 | '/users' : "Users pages",
2110 | '/about' : "About page"
2111 | }
2112 | const data = pages[url]
2113 | if(data){
2114 |
2115 | resolve(pages[url])
2116 | }
2117 | else{
2118 | reject({status:400})
2119 | }
2120 | },2000)
2121 | })
2122 | }
2123 |
2124 | fakeRequest('/users').then((data)=>{
2125 | console.log(data)
2126 | }).catch((res)=>{console.log(res.status)})
2127 | ```
2128 |
2129 | ## Promise Chaining
2130 | ```js
2131 | const fakeRequest = (url) => {
2132 | return new Promise((resolve, reject) => {
2133 | setTimeout(() => {
2134 | const pages = {
2135 | '/users': [
2136 | { id: 1, username: 'Tushar' },
2137 | { id: 5, username: 'Rahul' }
2138 | ],
2139 | '/users/1': {
2140 | id: 1,
2141 | username: 'Tushar',
2142 | country: 'India',
2143 | work: 'Noida',
2144 | role: 'Software Engineer',
2145 | postid: 54
2146 | },
2147 | '/users/5': {
2148 | id: 5,
2149 | username: 'Rahul',
2150 | country: 'India',
2151 | work: 'Noida',
2152 | role: 'DevOps Engineer'
2153 | },
2154 | '/posts/54': {
2155 | id: 54,
2156 | title: 'My new Post',
2157 |
2158 | },
2159 | '/about': "About page"
2160 | }
2161 |
2162 | const data = pages[url]
2163 | if (data) {
2164 | resolve(pages[url])
2165 | }
2166 | else {
2167 | reject({ status: 400 })
2168 | }
2169 | }, 2000)
2170 | })
2171 | }
2172 |
2173 | fakeRequest('/users').then((data) => {
2174 | let id = data[0].id;
2175 | return fakeRequest(`/users/${id}`)
2176 | })
2177 | .then((data) => {
2178 | // console.log(data)
2179 | let postid = data.postid;
2180 | return fakeRequest(`/posts/${postid}`)
2181 | })
2182 | .then((data) => {
2183 | console.log(data)
2184 | })
2185 | .catch((err) => { console.log(err) })
2186 | ```
2187 |
2188 |
2189 |
2190 |
Making http requests
2191 |
2192 |
XMLHTTP (old standard method)
2193 |
Fetch (a better way)
2194 |
Axios (a third party library)
2195 |
2196 | ## What is AJAX?
2197 | Asynchronous Javascript and XML.
2198 | AJAX is a technique for accessing web servers from a web page.
2199 |
Read data from a web server - after a web page has loaded
2200 |
Update a web page without reloading the page
2201 |
Send data to a web server - in the background
2202 |
2203 | ### AJAX just uses a combination of:
2204 | A browser built-in XMLHttpRequest object (to request data from a web server)
2205 | JavaScript and HTML DOM (to display or use the data)
2206 |
2207 |
2208 | AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
2209 |
2210 |
2211 |
2212 | 1. An event occurs in a web page (the page is loaded, a button is clicked)
2213 | 2. An XMLHttpRequest object is created by JavaScript
2214 | 3. The XMLHttpRequest object sends a request to a web server
2215 | 4. The server processes the request
2216 | 5. The server sends a response back to the web page
2217 | 6. The response is read by JavaScript
2218 | 7. Proper action (like page update) is performed by JavaScript
2219 |
2220 | ## XML and JSON
2221 | AJAJ- Asyncrhonous Javascript and JSON .
2222 |
2223 | XML and JSON are two ways of basically formatting data so that you can send it from a server to another server or a server to a browser.
2224 |
2225 | ### XML Format
2226 |
2227 | ```XML
2228 |
2229 | Tove
2230 | Jani
2231 | Reminder
2232 | Don't forget me this weekend!
2233 |
2234 | ```
2235 |
2236 | ### JSON Format
2237 | (JavaScript Object Notation)
2238 |
2239 | ```JSON
2240 | {
2241 | "employee": {
2242 | "name": "sonoo",
2243 | "salary": 56000,
2244 | "married": true
2245 | }
2246 | }
2247 | ```
2248 |
2249 |
JSON is not JS object
2250 |
Every key in JSON must be a string
2251 |
We can also use arrays in JSON
2252 |
We can easily translate between JSON to JavaScript
2253 |
2254 | ## XMLHttpRequest
2255 |
The "original" way of sending requests via JS.
2256 |
Does not support promises, so... lots of callbacks
2257 |
WTF is going on with the weird capitalization
2258 |
If the function returns a value, the promise will be resolved with that value.
2378 |
If the function throws an exception, the promise will be rejected.
2379 |
2380 | ```JS
2381 | async function hello(){
2382 | return "Hey Guys"
2383 | }
2384 | hello();
2385 | // Promise(: "Hey Guys")
2386 | async function huh(){
2387 | throw new Error("Oh no")
2388 | }
2389 | huh();
2390 | // Promise(: Error: oh no)
2391 | const add = async (a,b) => {
2392 | return a+b;
2393 | }
2394 |
2395 | add(24,35).then((value) => {console.log(value)})
2396 | ```
2397 |
2398 | ## The Await keyword
2399 |
We can only use the await keyword inside of function declared with async.
2400 |
Await will pause the execution of the function, waiting for a promise to be resolved.
2401 |
2402 | ```JS
2403 | async function getData(){
2404 | const res = await axios.get('https://swapi.dev/api/planets')
2405 | console.log(res.data)
2406 | }
2407 | ```
2408 |
2409 | ## Error handling in async Functions
2410 |
We can use catch while calling the async function as we know async functions always return promise.
2411 |
2412 | ```JS
2413 | getData().catch((err) => {console.log(err)})
2414 | ```
2415 |
2416 |
2495 |
2496 | ## What are protoypes?
2497 | Prototypes are the mechanism by which JavaScript objects inherit features from one another.
2498 |
2499 | ### A prototype-based language?
2500 | JavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.
2501 |
2502 | An object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them.
2503 |
2504 | We can define prototypes of string like
2505 |
2506 | ```JS
2507 | String.prototype.getup = function(){
2508 | return this.toUpperCase()
2509 | }
2510 | ```
2511 |
2512 | We can change already defined protoypes as well. For example
2513 |
2514 | ```JS
2515 | Array.prototype.pop = function(){
2516 | return "Sorry"
2517 | }
2518 | ```
2519 |
2520 | ## Object Oriented Programming in JavaScript
2521 |
2522 | There are certain features or mechanisms which makes a Language Object-Oriented like:
2523 |
2524 |
Object
2525 |
Classes
2526 |
Encapsulation
2527 |
Inheritance
2528 |
2529 | ###
Object
2530 | An Object is an instance of a class. Objects are everywhere in JavaScript almost every element is an Object whether it is a function, array, and string.
2531 |
2532 | >A Method in javascript is a property of an object whose value is a function.
2533 |
2534 | Object can be created in two ways in JavaScript:
2535 |
2536 |
Using an Object Literal
2537 |
2538 | ```JS
2539 | //Defining object
2540 | let person = {
2541 | first_name:'Mukul',
2542 | last_name: 'Latiyan',
2543 |
2544 | //method
2545 | getFunction : function(){
2546 | return (`The name of the person is
2547 | ${person.first_name} ${person.last_name}`)
2548 | },
2549 | //object within object
2550 | phone_number : {
2551 | mobile:'12345',
2552 | landline:'6789'
2553 | }
2554 | }
2555 | console.log(person.getFunction());
2556 | console.log(person.phone_number.landline);
2557 | ```
2558 |
2559 |
Using an Object Constructor
2560 |
2561 | ```JS
2562 | //using a constructor
2563 | function person(first_name,last_name){
2564 | this.first_name = first_name;
2565 | this.last_name = last_name;
2566 | }
2567 | //creating new instances of person object
2568 | let person1 = new person('Mukul','Latiyan');
2569 | let person2 = new person('Rahul','Avasthi');
2570 |
2571 | console.log(person1.first_name);
2572 | console.log(`${person2.first_name} ${person2.last_name}`);
2573 | ```
2574 |
2575 |
Using Object.create() method: The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
2576 |
2577 | ```JS
2578 | // Object.create() example a
2579 | // simple object with some properties
2580 | const coder = {
2581 | isStudying : false,
2582 | printIntroduction : function(){
2583 | console.log(`My name is ${this.name}. Am I
2584 | studying?: ${this.isStudying}.`)
2585 | }
2586 | }
2587 | // Object.create() method
2588 | const me = Object.create(coder);
2589 |
2590 | // "name" is a property set on "me", but not on "coder"
2591 | me.name = 'Mukul';
2592 |
2593 | // Inherited properties can be overwritten
2594 | me.isStudying = true;
2595 |
2596 | me.printIntroduction();
2597 | ```
2598 |
2599 | ###
Classes
2600 | Classes are blueprint of an Object. A class can have many Object, because class is a template while Object are instances of the class or the concrete implementation.
2601 |
2602 | ```JS
2603 | // Defining class using es6
2604 | class Vehicle {
2605 | constructor(name, maker, engine) {
2606 | this.name = name;
2607 | this.maker = maker;
2608 | this.engine = engine;
2609 | }
2610 | getDetails(){
2611 | return (`The name of the bike is ${this.name}.`)
2612 | }
2613 | }
2614 | // Making object with the help of the constructor
2615 | let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
2616 | let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
2617 |
2618 | console.log(bike1.name); // Hayabusa
2619 | console.log(bike2.maker); // Kawasaki
2620 | console.log(bike1.getDetails());
2621 | ```
2622 |
2623 | >unlike other Object Oriented Language there is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype based object oriented language, which means it doesn’t have classes rather it define behaviors using constructor function and then reuse it using the prototype.
2624 |
2625 | >JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.
2626 |
2627 | ###
Encapsulation
2628 | The process of wrapping property and function within a single unit is known as encapsulation.
2629 |
2630 | ```JS
2631 | //encapsulation example
2632 | class person{
2633 | constructor(name,id){
2634 | this.name = name;
2635 | this.id = id;
2636 | }
2637 | add_Address(add){
2638 | this.add = add;
2639 | }
2640 | getDetails(){
2641 | console.log(`Name is ${this.name},Address is: ${this.add}`);
2642 | }
2643 | }
2644 |
2645 | let person1 = new person('Mukul',21);
2646 | person1.add_Address('Delhi');
2647 | person1.getDetails();
2648 | ```
2649 | Sometimes encapsulation refers to hiding of data or data Abstraction which means representing essential features hiding the background detail.
2650 |
2651 | ###
Inheritance
2652 | It is a concept in which some property and methods of an Object is being used by another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript Object inherits Object i.e. certain features (property and methods)of one object can be reused by other Objects.
2653 |
2654 | ```JS
2655 | //Inheritance example
2656 | class person{
2657 | constructor(name){
2658 | this.name = name;
2659 | }
2660 | //method to return the string
2661 | toString(){
2662 | return (`Name of person: ${this.name}`);
2663 | }
2664 | }
2665 | class student extends person{
2666 | constructor(name,id){
2667 | //super keyword to for calling above class constructor
2668 | super(name);
2669 | this.id = id;
2670 | }
2671 | toString(){
2672 | return (`${super.toString()},Student ID: ${this.id}`);
2673 | }
2674 | }
2675 | let student1 = new student('Mukul',22);
2676 | console.log(student1.toString());
2677 | ```
2678 |
2679 | ## Factory Functions
2680 | ```JS
2681 | function makeColor(r, g, b) {
2682 | const color = {}
2683 | color.r = r;
2684 | color.g = g;
2685 | color.b = b;
2686 | color.rgb = function () {
2687 | const { r, g, b } = this;
2688 | return `rgb(${r}, ${b}, ${g})`
2689 | }
2690 | color.hex = function () {
2691 | const { r, g, b } = this;
2692 | return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
2693 |
2694 | }
2695 | return color;
2696 | }
2697 | ```
2698 |
2699 | This above function makes us an object. This is called factory function.
2700 |
2701 | ## Constructor funcion
2702 | Factory function pattern is not commonly used.
2703 | Instead of this we use constructor pattern or constructor function.
2704 |
2705 | ### The new operator
2706 | The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
2707 |
2708 |
2709 | new constructor[([arguments])]
2710 |
2711 |
2712 | ```JS
2713 | function Car(make,model,year){
2714 | this.make = make
2715 | this.model = model
2716 | this.year = year
2717 | }
2718 |
2719 | let car1 = new Car("Audi", "Q7", "2022")
2720 | ```
2721 |
2722 |
constructor
2723 | A class or function that specifies the type of the object instance.
2724 |
2725 |
arguments
2726 | A list of values that the constructor will be called with.
2727 |
2728 |
Creates a blank, plain JavaScript object.
2729 |
Adds a property to the new object (__proto__) that links to the constructor function's prototype object
2730 |
Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).
2731 |
Returns this if the function doesn't return an object.
2732 |
2733 |
2734 | ## Classes in JavaScript
2735 | Whenever we define a class, we define a constructor() inside of it. Constructor is a function which will run immediately when a object is created using this class.
2736 |
2737 | ```JS
2738 | class Color{
2739 | constructor(r,g,b){
2740 | console.log("INSIDE CONSTRUCTOR")
2741 | console.log(r,g,b)
2742 |
2743 | }
2744 | }
2745 |
2746 | const c1 = new Color(333,43,34)
2747 | ```
2748 |
2749 | We can define object methods in class
2750 |
2751 | ```JS
2752 | class Color{
2753 | constructor(r,g,b){
2754 | this.r = r
2755 | this.g = g
2756 | this.b = b
2757 | }
2758 | greet(){
2759 | const {r,g,b} = this
2760 | return `rgb(${r}, ${g}, ${b})`
2761 | }
2762 | }
2763 |
2764 | const c1 = new Color(333,43,34)
2765 | ```
2766 |
2767 | ## Extends, Super and Subclasses
2768 | We can inherit a class to another class using extends keyword
2769 |
2770 | ```JS
2771 | class Pet {
2772 | constructor(name,age){
2773 | this.name = name
2774 | this.age = age
2775 | }
2776 | eat(){
2777 | return `${this.name} is eating`
2778 | }
2779 | }
2780 |
2781 | class Cat extends Pet{
2782 | meow(){
2783 | return "MEOWWW"
2784 | }
2785 | }
2786 |
2787 | class Dog extends Pet{
2788 | bark(){
2789 | return "BARKWW"
2790 | }
2791 | }
2792 |
2793 | const cat1 = new Cat("Losi",5)
2794 | const dog1 = new Dog("Rockie",7)
2795 | ```
2796 |
2797 |
The super keyword is used to access and call functions on an object's parent.
2798 |
2799 | ```JS
2800 | class Rectangle {
2801 | constructor(height, width) {
2802 | this.name = 'Rectangle';
2803 | this.height = height;
2804 | this.width = width;
2805 | }
2806 | sayName() {
2807 | console.log('Hi, I am a ', this.name + '.');
2808 | }
2809 | get area() {
2810 | return this.height * this.width;
2811 | }
2812 | set area(value) {
2813 | this._area = value;
2814 | }
2815 | }
2816 |
2817 | class Square extends Rectangle {
2818 | constructor(length) {
2819 | this.height; // ReferenceError, super needs to be called first!
2820 |
2821 | // Here, it calls the parent class's constructor with lengths
2822 | // provided for the Rectangle's width and height
2823 | super(length, length);
2824 |
2825 | // Note: In derived classes, super() must be called before you
2826 | // can use 'this'. Leaving this out will cause a reference error.
2827 | this.name = 'Square';
2828 | }
2829 | }
2830 | ```
2831 |
2832 |
2833 |
2834 |
2835 |
JavaScript with Node.js
2836 |
2837 |
2838 |
2839 |
JS in Browser
2840 |
JS with Node
2841 |
2842 |
2843 |
Executed by adding script tags to an HTML document
2844 |
Executed by running the NODE CLI from your terminal
2845 |
2846 |
2847 |
We get access to the DOM and related objects(window)
2848 |
NO DOM exists
2849 |
2850 |
2851 |
Code can references variables in other files freely
2852 |
Each file is its own seperte world
2853 |
2854 |
2855 |
Include libraries by adding script tags(more complicated solutions exist)
2856 |
Include libraries by using NPM(Node Package Manager)
2857 |
2858 |
2859 |
2860 |
2861 | ## Running JS code with Node
2862 |
2863 | ```Bash
2864 | $ node index.js # executes a file in te same directory caled index.js
2865 |
2866 | $ node # enters the NODE REPS
2867 | ```
2868 |
2869 | ## Working with Modules in Node.js
2870 | If we want to share stuff between different node js files. We can make use of modules
2871 |
2872 | ```JS
2873 | // index.js
2874 | const message = require('./myscript.js')
2875 | console.log(message)
2876 | ```
2877 |
2878 | ```JS
2879 | // myscript.js
2880 | module.exports = 'Hi'
2881 | ```
2882 |
2883 | ```Bash
2884 | $ node index.js
2885 | ```
2886 |
2887 | ## Invisible functions
2888 | If we are running index.js file, node will find index.js file and then it's going to wrap it inside a function like this
2889 |
2890 | ```JS
2891 | function (exports, require, module,__filename, __dirname){
2892 | const message = require('./myscript.js')
2893 | console.log(message)
2894 | }
2895 | ```
2896 |
2897 | This is a simple function that has some number of arguments. This function is going to be automatically invoked by node. Here are 5 arguments that are automatically provided.
2898 |
2899 |
2900 |
2901 |
exports
2902 |
Equivalent to module.exports . We can technically export code using this, but it is easier to use 'module.exports' because of a little corner
2903 |
2904 |
2905 |
require
2906 |
Function to get access to the exports from another file
2907 |
2908 |
2909 |
module
2910 |
Object that defines some properties + informtion about the current file
2911 |
2912 |
2913 |
__filename
2914 |
Full path + file name of this file
2915 |
2916 |
2917 |
__dirname
2918 |
Full path of this file
2919 |
2920 |
2921 |
2922 | We can check these arguments by running -
2923 |
2924 | ```JS
2925 | console.log(arguments)
2926 | ```
2927 |
2928 | ## The require cache
2929 | Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
2930 |
2931 | > Moules get only required once.
2932 |
2933 | ## Debugging Node js
2934 |
2935 |
2936 |
node inspect index.js
2937 |
Start up a debugger CLI and pause execution whenever a debugger statement is hit
2938 |
2939 |
2940 |
node --inspect index.js
2941 |
start up a debugger instance and pause execution whenever a debugger statement is hit. Access the debugger at 'chrome://inspect'
2942 |
2943 |
2944 |
node --inspect-brk index.js
2945 |
Start up a debugger instance and wait to execute until a debugger is connected. Access the debugger at 'chrome://inspect'
Continue execution until program ends or next debugger statement
2955 |
2956 |
2957 |
n
2958 |
Run the next line of code
2959 |
2960 |
2961 |
s
2962 |
step in to a function
2963 |
2964 |
2965 |
o
2966 |
Step out of current function
2967 |
2968 |
2969 |
2970 | #### Accessing Node js standard library modules
2971 | We can access node js provided inbuilt standard library modules using require function.
2972 |
2973 | If we want to use file system we can require fs just like this
2974 |
2975 | ```JS
2976 | const fs = require('fs');
2977 | ```
2978 |
2979 | ## callback pattern in Node js
2980 | let's use fs.readdir function which accepts callbacks.
2981 |
2982 | If we want to use current directory, first argument we need to pass '.' in the function. The second argument is callback.
2983 |
2984 | ```JS
2985 | const fs = require('fs');
2986 | fs.readdir('.',(err,files)=>{
2987 | if(err){
2988 | console.log(err)
2989 | }
2990 | console.log(files)
2991 | })
2992 | ```
2993 |
2994 | ## Process.cwd function
2995 | cwd means current working directory.
2996 |
2997 | ```JS
2998 | const fs = require('fs');
2999 | fs.readdir(process.cwd(),(err,files)=>{
3000 | if(err){
3001 | console.log(err)
3002 | }
3003 | console.log(files)
3004 | })
3005 | ```
3006 |
3007 | ## Running a Node program as an Executable
3008 |
3009 | ```bash
3010 | $ npm init -y
3011 | ```
3012 | This command will generate a file for us, package.json
3013 |
3014 | ```JSON
3015 | {
3016 | "name": "project-1",
3017 | "version": "1.0.0",
3018 | "description": "",
3019 | "main": "index.js",
3020 | "scripts": {
3021 | "test": "echo \"Error: no test specified\" && exit 1"
3022 | },
3023 | "keywords": [],
3024 | "author": "",
3025 | "license": "ISC"
3026 | }
3027 | ```
3028 |
3029 | Here we can see a key "scripts" so these are tiny script that do some automated tasks for us.
3030 |
3031 | We can add another script that try to build our project
3032 |
3033 | ```JSON
3034 | "scripts": {
3035 | "test": "echo \"Error: no test specified\" && exit 1",
3036 | "build": "npm run build"
3037 | },
3038 | ```
3039 |
3040 | We can add bin key in this file so that when we run this nls command in our terminal our index.js file will be executed.
3041 |
3042 | ```JSON
3043 | "bin":{
3044 | "nls": "index.js"
3045 | }
3046 | ```
3047 |
3048 |
Add comment to index.js file to allow it to be treated like an executable
3056 |
3057 | ```JS
3058 | #!/usr/bin/env node
3059 | ```
3060 |
3061 |
Link our project
3062 |
3063 | ```bash
3064 | $ npm link
3065 | ```
3066 |
3067 | Now our project(index.js) file is executable. We can execute it from anywhere in our system just by command nls.
3068 |
3069 | > It's very useful for creating command line tools using node js.
3070 |
3071 |
3072 | ## Options to get to know which file is dir or file
3073 |
Maintain an array of results from each lstat. As each callback is invoked, add the stats object to this array. When array is full, log everything in it.
3074 |
Wrap the lstat call with a promise, use async/await syntax to process lstat call one at a time
3075 |
Wrap the lstat call with a promise, use async/await + the Promise.all helper method to process lstat calls all at once.
3076 |
3077 | let's implement most optimized solution(promise.all based)
3078 |
3079 | ```JS
3080 | #!/usr/bin/env node
3081 | const fs = require('fs');
3082 | const chalk = require('chalk')
3083 | const {lstat} = fs.promises;
3084 |
3085 | fs.readdir(process.cwd(),async (err,files)=>{
3086 | if(err){
3087 | console.log(err)
3088 | }
3089 | const fileAr = files.map((file)=>{return lstat(file)})
3090 | const stats = await Promise.all(fileAr)
3091 |
3092 | stats.forEach((stat,index)=>{
3093 | if(stat.isFile()){
3094 | console.log(chalk.blue(files[index]))
3095 | }
3096 | else{
3097 | console.log(chalk.green(files[index]))
3098 | }
3099 | })
3100 | })
3101 | ```
3102 |
3103 | ## Taking inputs from commandline
3104 |
3105 | If we console.log process.argv this will return an array and whatever we pass with our executable command that will be pushed into this array.
3106 |
3107 | ```JS
3108 | console.log(process.argv)
3109 | ```
3110 |
3111 |
3112 |
3113 | ### Thanks for reading this..
3114 |
3115 |
3116 |
3117 | ## Author: Tushar Rajpoot
3118 | ## Publication: Kubekode
3119 |
3120 |
Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas sint natus nostrum quas laudantium quasi ut
16 | voluptatem fugiat aliquid architecto. In distinctio expedita doloribus veritatis, vitae voluptates optio commodi
17 | itaque.
18 | Hell
19 |
20 |
Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloribus sint, magni dolorum sapiente voluptate
21 | quia
22 | praesentium autem! Veniam delectus, placeat excepturi in porro minima quo laudantium temporibus, aliquid repellendus
23 | similique.
24 |
25 |
30 |
31 | ADIJAKLSJDLKSAJLDKJL
32 |
33 |
34 |
First Thing
35 |
Second Thing
36 |
Third Thing
37 |
38 |
41 |
42 |
43 |
Carrots
44 |
Peas
45 |
Broccoli
46 |
47 |
48 |
49 |
50 |
56 |
57 |
TODO List
58 |
59 |
60 |
61 |
Mow the lawn
62 |
Milk the cows
63 |
Feed the alpacas
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/dom/insert.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tush-tr/learn-lang-javascript/515acb7e3606aa34182a1150893784d12dc412f5/dom/insert.js
--------------------------------------------------------------------------------
/dom/remove.js:
--------------------------------------------------------------------------------
1 | const ul = document.querySelector('ul')
2 | const removeMe = ul.querySelector('.special')
3 | ul.removeChild(removeMe)
4 |
--------------------------------------------------------------------------------
/functions/average.js:
--------------------------------------------------------------------------------
1 | // write a function to find the average value in an array of numbers.
2 | // avg([0,50]) // 25
3 | function avg(arr){
4 | const l = arr.length;
5 | // for(let i =0;i{
9 | return total+num;
10 | })
11 | return sum/l;
12 | }
13 | console.log(avg([0,50]));
14 |
--------------------------------------------------------------------------------
/functions/diceroll.js:
--------------------------------------------------------------------------------
1 | function diceRoll(){
2 | let roll = Math.floor(Math.random()*6)+1;
3 | console.log(roll);
4 | }
5 |
--------------------------------------------------------------------------------
/functions/funcargs.js:
--------------------------------------------------------------------------------
1 | function callTwice(func){
2 | func();
3 | func();
4 | }
5 |
6 | function laugh(){
7 | console.log("hahahahahhah");
8 | }
9 |
10 | callTwice(laugh);
--------------------------------------------------------------------------------
/functions/getcard.js:
--------------------------------------------------------------------------------
1 | /*
2 | write a getCard() function which returns a random playing card object, like
3 | {
4 | value: 'K',
5 | suit: 'clubs'
6 | }
7 | pick a random value from
8 | -- 1,2,3,4,5,6,7,8,9,10,J,Q,K,A
9 | pick a random quit from
10 | clubs, spades, hearts, diamonds
11 | return both in an object
12 | */
13 | function getCard(){
14 | let value;
15 | let randNum = Math.floor(Math.random()*14)+1;
16 | if(randNum===11){
17 | value = 'J';
18 | }
19 | else if(randNum===12){
20 | value = 'Q';
21 | }
22 | else if(randNum===13){
23 | value = 'K';
24 | }
25 | else if(randNum===14){
26 | value = 'A';
27 | }
28 | else{
29 | value = randNum;
30 | }
31 | let suit;
32 | let randSuit = Math.floor(Math.random()*4)+1;
33 | switch(randSuit){
34 | case 1:
35 | suit= 'clubs';
36 | break;
37 | case 2:
38 | suit = 'spades';
39 | break;
40 | case 3:
41 | suit = 'hearts';
42 | break;
43 | case 4:
44 | suit = 'diamonds';
45 | break;
46 | }
47 | return {value: value,suit: suit}
48 | }
49 | console.log(getCard())
--------------------------------------------------------------------------------
/functions/higherorder.js:
--------------------------------------------------------------------------------
1 | function add(x,y){
2 | return x+y;
3 | }
4 | const subtract = function(x,y){
5 | return x-y;
6 | }
7 |
8 | function multiply(x,y){
9 | return x*y;
10 | }
11 | const divide = function(x,y){
12 | return x/y;
13 | }
14 | // let's add all these functions to an array
15 | const operations = [add,subtract,multiply,divide];
16 | // now we can use this array of functions like this:
17 | // console.log(operations[0](3,4)) //7
18 | for(let func of operations){
19 | console.log(func(12,34));
20 | }
21 | // now I can also add these functions into an object and create a method
22 | const thing = {
23 | doSomething: multiply
24 | }
25 | // now I can call and use this function as a method of object
26 | console.log(thing.doSomething(23,3));
27 |
28 |
29 |
--------------------------------------------------------------------------------
/functions/makebetween.js:
--------------------------------------------------------------------------------
1 | function makeBetweenFunc(min,max){
2 | return function (val){
3 | return val>=min && val<=max;
4 | }
5 | }
6 | const inAgeRange = makeBetweenFunc(18,100);
7 | console.log(inAgeRange(45));
--------------------------------------------------------------------------------
/functions/operations.js:
--------------------------------------------------------------------------------
1 | function add(x,y){
2 | return x+y;
3 | }
4 | const subtract = function(x,y){
5 | return x-y;
6 | }
7 | function multiply(x,y){
8 | return x*y;
9 | }
10 | const divide = function(x,y){
11 | return x/y;
12 | }
13 | function operations(oper,x,y){
14 | return oper(x,y);
15 | }
16 | console.log(operations(add,2,3)); // 5
17 | console.log(operations((a,b)=>{
18 | return a+b;
19 | },45,5)); // 50
20 |
21 |
--------------------------------------------------------------------------------
/functions/pangram.js:
--------------------------------------------------------------------------------
1 | /*
2 | a pangram is a sentence that contains every letter of the alphabet,
3 | write a function called isPangram, which checks to see if a given sentence contains every letter of the alphabet.
4 | */
5 | function isPangram(sentence){
6 | sentence = sentence.toLowerCase();
7 | for(let char of 'abcdefghijklmnopqrstuvwxyz'){
8 | if(sentence.indexOf(char)===-1){
9 | return false;
10 | }
11 | }
12 | return true;
13 | }
14 | console.log(isPangram('Sphinx of black quartz, judge my vow.'))
--------------------------------------------------------------------------------
/functions/passwordvalidator.js:
--------------------------------------------------------------------------------
1 | /*
2 | write a isValidPassword function.
3 | accepts two arguments: password and username
4 | password must:
5 | - be at least 8 characters
6 | - can't contain spaces
7 | - can't contain the username
8 | if all requirements are met, return true, otherwise false
9 |
10 | isValidPassword('89Fjjlnms','dogluvr'); // true
11 | */
12 |
13 | function isValidPassword(password, username){
14 | const tooShort = password.length<8;
15 | const containspace = password.indexOf(' ')!==-1;
16 | const containusername = password.indexOf(username)!== -1;
17 | if(tooShort || containspace || containusername){
18 | return false;
19 | }
20 | return true;
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/functions/returnfunc.js:
--------------------------------------------------------------------------------
1 | function multiplyBy(num){
2 | return function(a){ // anonymous function
3 | return a*num;
4 |
5 | }
6 | }
7 | const triple = multiplyBy(3);
8 | console.log(triple(20)); // 60
9 | console.log(multiplyBy(3)(20)); // 60
--------------------------------------------------------------------------------
/http-requests/axios/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |