forked from sanjaysamantra1/javascript_programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSanjay_JS.txt
More file actions
1547 lines (1146 loc) · 54.7 KB
/
Sanjay_JS.txt
File metadata and controls
1547 lines (1146 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
HTML - content of a webpage
CSS - for styling
Bootstrap - Responsiveness + pre-defined components-table,carousel,modal,card
Javascript - behaviour of a webpage
Javascript
==========
-dynamically typed , Synchronous & single-threaded Programming Language.
-dynamically typed means the types are checked, and datatype mismatches are spotted only at the runtime.
-JavaScript engine executes code from top to bottom, line by line.In other words, it is synchronous.
-JavaScript engine has only one 'call-stack' so that it only can do one thing at a time.
-A JavaScript engine is a program or an interpreter which executes JavaScript code.
javascript Engines:
V8 - is developed by Google , Google Chrome.
SpiderMonkey - is developed by Mozilla , Firefox.
JavaScriptCore - is Apple's engine for its Safari browser.
Chakra - is the JavaScript engine of the Internet Explorer browser.
Types
------
1. internal
a. <script></script>
b. head or body
c. page level javascript
2. external
a. separate js file(needs to be included to html)
<script src='abc.js'></script>
b. head or body
c. Application level/project level
Q. What is the best place to include js files? head/body?
Eliminate Render-Blocking JavaScript
====================================
-With HTML5, we got two new boolean attributes for the <script> tag : async and defer.
ex:- <script src='demo.js' async/defer></script>
-async/defer attribute should only be used on external scripts, not with internal scripts.
-These attributes only make sense while using the script in the head portion of the page.
-A good strategy is to use async when possible, and then defer when async isn’t an option.
-With async, the file gets downloaded asynchronously and then executed as soon as it’s downloaded.
-With defer, the file gets downloaded asynchronously, but executed only when the document parsing is completed.
-With defer, scripts will execute in the same order as they are called.
defer is useful when a script depends on another script.
https://flaviocopes.com/javascript-async-defer/
Javascript - is a programming language, follows ECMASCRIPT Standards.
ECMA - European Computer Manufacturers Association.
ECMASCRIPT - is a standard for the scripting languages.
Javascript TypeScript
---------------------------------------------------------
1.strongly typed-No 1.strongly typed-yes
2.directly run on browser 2.not directly run on the browser
3.interface-No 3.interface - Yes
4.optional parameters-No 4.optional parameters-yes
5.interpreted language 5.compiles the code
6.errors at runtime 6.errors during the development time
7.generics-no 7.generics-yes
datatypes:
=========
-Types of data we are dealing with.
-JavaScript provides different data types to hold different types of values.
-two types of data types :
1.primitive (number,string,boolean,undefined,null,symbol,bigInt)
2.Non-primitive (object references - Object)
-difference between primitives and non-primitives is that primitives are immutable and
non-primitives are mutable.
var str = 'This is a string.';
str[1] = 'H'
console.log(str); // 'This is a string.'
-Mutable values are those which can be modified after creation.
-Immutable values are those which cannot be modified after creation.
-primitives are compared by values whereas non-primitives are compared by references.
-primitive value will always be exactly equal to another primitive with an equivalent value.
const first = "abc" + "def";
const second = "ab" + "cd" + "ef";
console.log(first === second); // true
-equivalent non-primitive values will not result in values which are exactly equal.
const obj1 = { name: "sanjay" };
const obj2 = { name: "sanjay" };
console.log(obj1 === obj2); // false
-'typeof' is used to check datatype of a value.
Primitive Non-primitive/Complex
-------------- -------------------------
1. number 1. function
2. string 2. Object ( {} ,[] )
3. boolean(true,false)
4. undefined(undefined)
5. null
6. symbol(ES-6)
7. bigint (const x = 2n ** 53n;)
appending n to the end of an integer literal
null vs undefined
------------------
-undefined means "not initialized".it means a variable is declared but not initialized yet.
-null means "the intentional absence of any object value". null is an assigned value. It means nothing.
-A variable initialized with undefined means that the variable has no value or object assigned to it
while null means that the variable has been set to an object whose value is undefined.
-Both null and undefined are falsy values.
-The JSON data format does not support undefined, supports only null;
-JSON.stringify({a: undefined, b: null}) -->{"b":null}
-even though typeof null === 'object', null is a still primitive value.
ex: null == null; //true
1. when a variable is declared without a value, that variable by default will have undefined value
a variable can be declared with a null value.
var a; //a=undefined
var b = null; //b=null
2. typeof undefined; // undefined
typeof null; //object
var a = {}
var b = []
typeof a; //object
typeof b; //object
a instanceof Object; //true
b instanceof Object; //true
a instanceof Array; //false
b instanceof Array; //true
Array.isArray(a); //false
Array.isArray(b); //true
Symbol
======
-A 'symbol' represents a unique identifier.
-Symbols are often used to add unique property keys to an object that won’t collide with keys.
-create a symbol by calling the Symbol(), not by using new keyword.
let sym1 = Symbol() // correct
let sym2 = new Symbol() // TypeError
-Even if we create many symbols with the same description, they are different values.
Symbol('foo') === Symbol('foo') // false
-Symbols allow us to create “hidden” properties of an object,
that no other part of code can accidentally access or overwrite.
-If we want to use a symbol in an object literal,we need square brackets around it.
let id = Symbol();
let user = {name:'sanjay',[id]:123}
-Symbols are not enumerated,Symbols are skipped by for…in while we iterate object properties.
-Symbols are not part of the Object.keys() or Object.getOwnPropertyNames()
-Symbols assigned to an object can be accessed using the Object.getOwnPropertySymbols() method
-Object.assign() copies both string and symbol properties.
Type coercion/Type casting
==========================
-Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).
-Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference
-type coercion is implicit whereas type conversion can be either implicit or explicit.
Rules:
-Primitives are coerced to string when using the binary + operator —
if any operand is a string
-Primitives are coerced to number when using comparison operators.
"5" >= 1 true
-Primitives are coerced to number when using arithmetic operators (except for + when one operand is a string)
"5" - 1 4
"5" * 3 15
-Primitives are coerced to number when using the unary + operator
+'123' 123
+true 1
+null 0
Most Used methods in JS
=======================
window.alert() - window(Object), alert(function)
document.write() - document(object), write(function)
console.log() - console(object), log(function)
window - alert(),confirm(),prompt(),setTimeout(),setInterval(),print(),open()
document - write(),writeln(),getElementById(),querySelector()
console - log(),error(),warn(),table(),dir(),trace(),count(),time(), timeEnd(),group()
N.p - while calling window object functions it is not necessary to call with object name;
window.alert(); // correct
alert(); // correct
this.alert(); // correct
console.log() // Yes
log() // No
document.write(); //yes
write(); //No
Note:- all window Object functions can be directly called.
default value of 'this' is 'window'
How Javascript Works
====================
-When JavaScript engine executes a script, it creates N execution contexts.
-execution context is the environment within which the current code is being executed.
-Each execution context has two phases:
1. creation phase. (Allocates memory - variables & functions and assign 'undefined' to variables)
2. execution phase. (Code gets Executed - assign values to variables & method invocation)
-When a script executes for the first time,JavaScript engine creates a 'Global Execution Context' and pushes to callstack.
-For every function call,JavaScript engine creates a new Function Execution Context and that gets added to callstack.
https://www.youtube.com/watch?v=iLWTnMzWtj4&t=1044s
https://www.jsv9000.app/
Variables
=========
-Variables are containers for storing data values.
Variable is a name of memory location.
-Variables in Javascript can be declared by using either one of the below 3 keywords:
1. var
2. const
3. let
var let const
======================================================================
1.since begining 1.ECMASCRIPT-6(2015) 1.ECMASCRIPT-6(2015)
2.value can be changed 2.value can be changed 2.cann't be changed
3.initialization is 3.initialization is 3.mandatory
not mandatory not mandatory
4.can be redeclared 4.cann't be redeclared 4.cann't be redeclared
5.hoisting-yes 5.hoisting-no(TDZ) 5.hoisting-no(TDZ)
6.function scope 6.block scope 6.block scope
N:p - All variables (var,let,const) are hoisted but only 'var' variables are usable/reachable before declaration.
-let/const variables are not reachable/usable before declaration (Temporal Dead Zone)
Hoisting:
=========
-The process of assigning variable declarations a default value of 'undefined' during
the creation phase is called Hoisting.
-In hoisting, the variable and function declarations are put into memory during the
compile/creation phase before code execution phase.
-variables can be initialized and used before they are declared.
-JavaScript only hoists declarations, not initializations.
-variable hoisting works for var, not for let/const. (Temporal Dead Zone)
-function declareations are hoisted, Function expressions and arrow functions aren’t hoisted.
https://www.idontknowjavascript.com/2019/05/javascript-hoisting-interview-question.html
Temporal Dead Zone
==================
-The period between entering scope and being declared where they cannot be accessed.
This period is the temporal dead zone (TDZ).
-the state where variables are un-reachable. They are in scope, but they aren't declared.
-The let and const variables exist in the TDZ from the start of their enclosing scope until they are declared.
-if a let/const variable is accessed before its declaration, it would throw a ReferenceError. Because of the TDZ.
What’s the difference between context and scope?
===============================================
-The context is (roughly) the object that calls the function.
-And the scope is all the variables visible to a function where it is defined.
-One cares about how it is called, the other cares about how it is defined.
variable scope:
==============
-Scope is a certain section/region of the program where a defined variable can have its existence and can be recognized, beyond that it can’t be accessed.
-Scope determines the visibility and accessibility of a variable.
-Every variable will have either 1 of the below 3 scopes.
1. global
2. function/Local
3. block
global scope:
--------------
-variables declared outside function.
-these are accesible/visible throughout the script by any function.
function:
--------
-declared inside a function/function arguements.
-can be used only inside that function.
block scope:
------------
-declared inside a block(if,else,try,catch)
-visible only inside a block
N.P-Scope of the variables declared without var/let/const become global irrespective of
where it is declared.
Scope chain
===========
-While resolving a variable, the block first tries to find it within the own scope.
-If the variable cannot be found in its own scope it will climb up the scope chain and look for the variable name in the environment where the function was defined.
-If the variable cannot be found there, it will climb up the scope chain and will go till global scope to resolve the variable.
Variable Shadowing
==================
-when a variable is declared in a certain scope having the same name defined on its
outer scope and when we call the variable from the inner scope, the value assigned to
the variable in the inner scope is the value that will be stored in the variable in
the memory space. This is known as Shadowing.
-while shadowing a variable, it should not cross the boundary of the scope, i.e. we can
shadow var variable by let variable but cannot do the opposite. So, if we try to shadow
let/const variable by var variable, it is known as Illegal Shadowing and it will give the error as “variable is already defined.”
UseStrict
=========
-provides better coding standard and stronger error checking.
-'use strict' is only recognized at the beginning of a script or a function.
-The purpose of "use strict" is to execute the javascript in "strict mode".
-when 'use strict' is not written, browser runs the JS in normal mode.
-when 'use strict' is written, browser runs the JS in strict mode.
-Strict mode changes some previously-accepted mistakes into errors.
1. variable declaration without var/let/const is not allowed.
makes it impossible to accidentally create global variables.
2. function with duplicate arguements are not allowed.
3. NaN/undefined/Infinity cann't be used as a variable name.
4. undeletable properties cann't be deleted.
ex:delete Object.prototype;
var x = 5; delete x;
5. Multiple assignments not allowed.
var a = b = c = 3;
6. 'this' is undefined, when a function is invoked from Global Context in strict mode.
Comments
========
-it improves readability/understandability of a file.
-single line comment
// single line comment (ctrl + /)
-multi line comment ( Alt + Shift + a)
/*
line-1
line-2
line-3
*/
Operators
=========
1. arithmetic (+,-,*,/,%,**) /quotient %remainder **exponent
2. Assignment (=,+=,-=,*=)
3. Relational (>,>=,<,<=,==,===,!=,!==)
4. logical (&&,||,!)
5. bitwise (&,|,^,~)
6. increment/decrement (++,--)
7. miscelaneous (typeof,instanceof)
No of operands
---------------
1. unary (1 operand) ex: -5 , ++a
2. binary (2 operands) ex: a+b , x-y
3. ternary (3 operands) ex: a>b ? a : b;
res = condition ? trueValue : falseValue;
== compares only the value, performs implicit type conversion. (equality)
=== compares both value and datatype, no type conversion is performed.(Strict equality)
Note: === (Strict equality) is faster as no type conversion is performed
pre-increment(++a)
post-increment(a++)
pre-decrement(--a)
post-decrement(a--)
Q. using ternary operator find the greatest number amongst 3 numbers
dialog boxes/popup boxes
========================
the below functions are from 'window' object
1. alert() - display Message
(message + ok)
2. confirm()- User Confirmation
( message + ok-true,cancel-false)
3. prompt()- Collect User Input
(message + inputBox + ok,cancel)
conditional statements
======================
1. if
2. if-else
3. switch
Loop
====
Loop helps to execute a block of statements/code number of times.
1. while
2. do-while (usefule to output some sort of menu, the menu is guaranted to show once)
3. for
Functions
=========
-function is a block of code/statements designed to perform a particular task.
-function is executed only when that gets invoked/called.
-function is defined with the function keyword, followed by a name, followed by parentheses ().
-The code to be executed(function body), by the function, is placed inside curly brackets: {}
-Function parameters are listed inside the parentheses () in the function definition.
-Function arguments are the values received by the function when it is invoked.
-Inside the function, the arguments (the parameters) behave as local variables.
1. pre-defined (alert(),prompt(),confirm(),max(),min(),sqrt(),cbrt())
already written, we are just using them
2. user-defined
we have to write,and we will use them
a. function declaration (named function)
b. function expression(anonymous)
c. self invoked ( IIFE- Immediately Invoked Function Expression)
d. arrow function (ES - 6)
Note:
=====
Parameter: is the variable in the function declaration.
It is part of the function signature when you create it.
Argument: is the actual value of the variable being passed to the function when it is called.
Function Declaration Function Expression
--------------------------------------------------------
1. Named 1. Anonymous
2. Hoisting - yes 2. Hoisting - No
3. creation phase(parse) 3. execution phase (run)
-A Function Expression is created when the execution reaches it and is usable only from that moment.
-A Function Declaration can be called before it is defined.
-function declarations are parsed before their execution.
function expressions are parsed only when the script engine encounters it during execution.
Arrow Function
--------------
-'this' value inside a regular function is dynamic and depends on the context in which it is called.
-'this' inside the arrow function is bound lexically and equals to 'this' where the function is declared.
-lexical context means that arrow function uses 'this' from the code that contains the arrow function.
-arrow function doesn’t define its own execution context.
-Regular function ( this = how the function is invoked/who invoked )
-Arrow function( this = where the function is declared )
Arrow Function Limitations
--------------------------
-Arrow functions don't have their own bindings to this, arguments or super, and should not be used as methods.
-Arrow functions don't have access to the new.target keyword.
-Arrow functions aren't suitable for call, apply and bind methods, which generally rely on establishing a scope.
-Arrow functions cannot be used as constructors.
-Arrow functions cannot use yield, within its body.
IIFE
====
-used when we try to avoid polluting the global scope,
-The variables declared inside the IIFE are not visible outside its scope.
-closure
Function Curring
================
-Function Currying is a concept of breaking a function with many arguments into many functions with single argument in such a way, that the output is same.
-its a technique of simplifying a multi-valued argument function into single-valued argument multi-functions.
-It helps to create a higher-order function. It is extremely helpful in event handling.
var add = function (a){
return function(b){
return function(c){
return a+b+c;
}
}
}
console.log(add(2)(3)(4)); //output 9
Pure Function
=============
-Pure functions are functions that accept an input and returns a value without
modifying any data outside its scope(Side Effects).
-A function is called pure if that follows the below 3 standards
1. Pure functions shouldn't update the data outside it's scope.
2. pure functions must return a value.
3. Its output or return value must depend on the input/arguments.
Higher-order Function
=====================
-Higher-order function is a function that may receive a function as an argument and/or
can even return a function.
-a function can be called as a Higher-order if that function has either of the below 2 abilities:
1. a function has ability to return another function.
2. a function has ability to take another function as argument.
-Array filter(),map(),reduce(),sort() are some of the Higher-Order functions.
function recursion
==================
-A recursive function is a function that calls itself until the program achieves the desired result.
-A recursive function should have a condition that stops the function from calling itself.otherwise, 'RangeError: Maximum call stack size exceeded' error will be thrown
-A recursive function can be used instead of a loop where we don't know how many times the loop needs to be executed.
ex: function countDown(fromNumber) {
console.log(fromNumber);
let nextNumber = fromNumber - 1;
if (nextNumber > 0) {
countDown(nextNumber);
}
}
countDown(5);
Memoization
===========
-Memoization is a programming technique that attempts to increase a function’s performance by caching its previously computed results.
-Memoization is an optimization technique used to speed up performance by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
-its a kind of caching the data.
-used with recursion.
function closure
****************
-A closure is an inner function that has access to its outer function's variables
even after the outer function's execution is completed.
-A closure is the combination of a function bundled with the lexical environment within
which that function is declared.
-a closure gives access to an outer function’s scope from an inner function.
-closures are mainly used for - encapsulation , iterators
-closure = function + lexical-scope
Closure Disadvantages
=====================
-As long as the closure are active , the memory can't be garbage collected.
-If we are using closure in ten places then unless all the ten process complete
it hold the memory which cause memory leak.
Number
======
isInteger();
isNaN()
parseInt();
parseFloat();
Math
=====
Math.PI;
abs();
sqrt();
cbrt();
ceil();
floor();
round();
max();
min();
pow();
random(); // 0.0 - 1.0
Strings
=======
-strings are used to represent and manipulate a sequence of characters.
-JavaScript string is zero or more characters written inside quotes.
-We can use single or double quotes for string.
var a='hello';
var b="hello";
-We can use quotes inside a string, as long as they don't match the quotes surrounding the string.
var answer1 = 'It's alright'; //in-valid
var answer1 = "It's alright"; //valid
var answer2 = "He is called 'Johnny'"; //valid
var answer3 = 'He is called "Johnny"'; // valid
-Strings can be created in 2 ways
1. as primitives, using string literals;
var a = 'hello';
2. as objects, using the String() constructor
var b = new String('hello');
-JavaScript automatically converts primitives to String objects, so that it's possible
to use String object methods for primitive strings.
-String primitives and String objects give different results when using eval().
Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object..
let s1 = '2 + 2' // creates a string primitive
let s2 = new String('2 + 2') // creates a String object
console.log(eval(s1)) // returns the number 4
console.log(eval(s2)) // returns the string "2 + 2"
-A String object can always be converted to its primitive counterpart with the valueOf() method.
console.log(eval(s2.valueOf())) // returns the number 4
1. literal
var str1 = "sachin";
typeof str1; //string
2. object
var str2 = new String("sachin");
typeof str2; //"object"
var a = "sachin";
var b = "sachin"
a == b; // true
var a = "sachin";
var b = new String("sachin")
a == b; // true
var a = new String("sachin");
var b = new String("sachin");
a == b; // false
String methods:
--------------
length;
toUpperCase();
toLowerCase();
charAt();
charCodeAt();
concat();
indexOf();
lastIndexOf();
includes();
match();
replace();
replaceAll();
slice(start, end)
substring(start, end)
substr(start, length)
split()
search(regex)
trim()
eval(); (eval() is from Window Object)
N.p:- substring() cannot accept negative indexes. slice() does.
Array
=====
-Arrays are used to store multiple values in a single variable.
ex: var arr = [10,20,30,40,50]
-An array can hold many values under a single name,
and we can access the values by referring to an index number.
ex: console.log(arr[1]);
-Usually in other programming languages array stores similar type of elements,but in
JavaScript array can have heterogeneous elements.
ex: var arr = [10,'sachin',true,{}]
array creation:
---------------
var marks = [10,20,30,40,50];
var arr1 = new Array(5);
var arr2 = new Array(10,20,30,40,50);
-iterating over an array: 1.loop 2.for-in 3.for-of 4.forEach()
properties: length , delete
instance functions: at(),concat(),entries(),every(),fill(),filter(),find(),findLast(),findIndex(),flat(),
flatMap(),forEach(),includes(),indexOf(),join(),keys(),lastIndexOf(),map(),pop(),push()
reduce(), reverse(), shift(),slice(),sort(),some(), splice(),unshift(),values()
static functions : from(),isArray(),of()
To add/remove elements:
push(...items) – adds items to the end,
pop() – extracts an item from the end,
shift() – extracts an item from the beginning,
unshift(...items) – adds items to the beginning.
splice(pos, deleteCount, ...items) – at index pos delete deleteCount elements and insert items.
slice(start, end) – creates a new array, copies elements from position start till end (not inclusive) into it.
concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of items is an array, then its elements are taken.
To search among elements:
at(index) - takes an integer and returns the item at that index.allows negative index aswell.
indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.
includes(value) – returns true if the array has value, otherwise false.
find(func) – filter element through the function, return first value that make it return true.
findLast(func) – filter element through the function, return last value that make it return true.
filter(func) – filter elements through the function, return all values that make it return true.
findIndex(func) - it is like find(), but returns the index instead of a value.
To transform the array:
map(func) – creates a new array from results of calling func for every element.
sort(func) – sorts the array in-place, then returns it.
reverse () – reverses the array in-place, then returns it.
split/join – convert a string to array and back.
reduce(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.
flat() - creates a new array with the elements of the subarrays concatenated into it.flat(Infinity) , flat() also removes holes in array
flatMap() - maps each element in an array using a mapping function and then flattens the results into a new array
To iterate over elements:
forEach() – calls func for every element, does not return anything.
Additionally:
Array.isArray(arr) checks arr for being an array.
Array.from() change array-like or iterable into true array
Array.of() create array from every arguments passed into it.
const nums = Array.of(1, 2, 3, 4, 5, 6);
console.log(nums);
let mySet = new Set()
mySet.add(2).add(3).add(4);
console.log(Array.from(mySet))
const lis = document.querySelectorAll('li');
const lisArray = Array.from(document.querySelectorAll('li'));
// is true array?
console.log(Array.isArray(lis)); // output: false
console.log(Array.isArray(lisArray)); // output: true
var arr = [10,20,30]
var x = arr.values();
console.log(x)
var y = Array.from(x)
console.log(y)
OOP
----
class - structure/blueprint/template for creating Object
class has only logical existance
class doesn't have physical existance
object - Real Entity
every instance of a class
Object has physical existance
-a class in javascript is created using constructor function(ES-5).
-a class in javascript is created using class keyword.(ES-6).
-class contains variables(states/properties) and methods(behaviours) inside it.
Prototype
---------
-A prototype is an object used to implement structure, state, and behaviour inheritance in ECMAScript
-Prototype is the mechanism by which JavaScript objects inherit features from one another
-Prototype is an object, where we can attach methods and properties
,which enables all the other objects to inherit these methods and properties
-Prototype is a base class for all the objects, and it helps us to achieve inheritance.
-All JavaScript objects inherit properties and methods from a prototype.
-properties added to the prototype of a class gets available to
all the objects of that class.
-prototype should be used When we have to add new properties like variables and methods
at a later point of time,and these properties needs to be shared across all the instances,
-a property should be added to the constructor of a class if value of the property changes per object
-a property should be added to the prototype of a class if the value remains same for all objects.
Inheritance
-----------
- Inheritance is the concept where one class inherits the properties
from another class.
- the class which inherits properties is called child/derived/sub.
the class which provides the properties is called parent/base/super.
- it is mainly used for code re-usability.
- also called is-a relationship
Object class
============
-Objects are variables that can contain many values inside it.
-The values are written as 'key:value' pairs.
ex: let user = {name:'sachin' , age:35}
-we can access object properties in two ways:
objectName.propertyName; user.name;
objectName["propertyName"]; user['age'];
-4 ways to create javascript object
1. Object Literal ex: var obj1 = {};
2. Object create() ex: var obj2 = Object.create({});
3. Object Class ex: var obj3 = new Object();
4. Using Class ex: var obj4 = new Employee();
-How to get the length of the object
Object.keys(obj).length;
-How to check if a property exists in an object
console.log(propertyName in obj) (also includes prototype properties)
obj.hasOwnProperty(propertyName) (doesn't includes prototype properties)
-Object class static functions :
assign() - Copies properties from one or more source objects to a target object.
create() - creates a new object, using an existing object as the prototype of the newly created object
freeze() - Freezes an object. neither the structure nor values can be changed
isFrozen() - Determines if an object was frozen
seal() - structure of the object cann't be modified, value of the properties can be changed.
isSealed() - Determines if an object is sealed.
preventExtensions() -new properties cann't be added to an object, properties can be deleted
isExtensible() - Determines if extending of an object is allowed
keys() - Returns an array of keys
values() - Returns an array of values
entries() - returns an array of [key, value] pairs
fromEntries() - transforms an array/Map into an Object
-JSON.stringify() converts object to string.
-JSON.parse() converts string to object.
-shallow copy : Object.assign()
obj2 = {...obj1}
-deep cloning : JSON.parse(JSON.stringify(obj))
obj2 = structuredClone(obj1)
-A shallow copy of an object is a copy whose nested properties share the same references.
(Nested objects will not be copied by value)
-A deep copy of an object is a copy whose nested properties do not share the same references.
this keyword
------------
-'this' is the context of a function invocation/execution.
-In the global execution context (outside of any function), 'this' refers to the
global object whether in strict mode or not.
-'this' is undefined in a function invocation in strict mode.
-'this' is the object that owns the method(not arrow function) in a method invocation.
the object becomes value of 'this'. myObj.myMethod();
-'this' is the newly created object in a constructor invocation.
-'this' is the first argument of .call() or .apply() in an indirect invocation.
-'this' is the first argument of myFunc.bind(thisArg) when invoking a bound function.
-'this' is the enclosing context where the arrow function is defined.
-Inside a setTimeout function, the value of this is the window object.
-For dom event handler, value of this would be the element that fired the event.
note:- You can always get the global object(window) using 'globalThis' property,
regardless of the current context in which your code is running.
Call() & apply() & bind()
========================
-call(),apply(),bind() are methods from 'Object' class.
-used to change the context while calling a function.
call() - call() is used to pass differenet object as a value to 'this'.
call() method calls a function with a given 'this' value and arguments provided individually.
used to change the context while calling a function.
using call() one object can invoke another object's function.
apply() - apply() takes 2 arguments.1st arguement is an object(this), 2nd arguement is an array of items.
-it takes the values from that array and passes as individual arguements to a method.
-bind() creates a new function and when that(new function) is called will have its
'this' set to the provided value with a given sequence of arguements.
-it is most useful for binding the value of 'this' in methods of classes
that you want to pass into other functions.
ES-6 Features (ES-2015)
=======================
1. const & let
2. From IIFEs to blocks
3. concatenating strings to template literals
4. Multi-line strings
6. default parameter values
7. from arguments to rest parameters
8. exponent operator (**)
9. Desturcturing (array/object)
10. for-loop to for-in and for-of
11. arrow functions
12. From apply() to the spread operator (...)
13. From function expressions in object literals to method definitions
14. From constructors to classes
15. inheritance - class,extends
16. Modules
17. collection-Map,weakmap,set,weakset
18. promise and async-await
19. generators
20. Tail Calls
Event Handling
--------------
- onclick,ondblclick,onmouseover,onmouseout (Mouse)
- onkeypress , onkeydown, onkeyup (Keyboard)
- onsubmit, onchange, onblur,onfocus,onpaste,oncopy (Form)
- onload, onbeforeUnload , onunload (Document)
addEventListner
---------------
1. to add events to dynamically added elements.
2. to add multiple events to an element.
Event Delegation
----------------
-Event delegation allows to add event listeners to one parent instead of
adding event listeners to many child elements.
-That particular listener analyzes bubbled events to find a match on the child elements.
Event Propagation:-
1. event Capturing (parent-->child)
2. event Bubbling (child-->parent)
bubbling:
--------
-When an event gets triggered on an element, it first runs the handlers on it, then on
its parent, then all the way up on other ancestors/parents. (Event Bubbling)
-Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element
inside another element, and both elements have registered a handle for that event.
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. The execution starts from that event and goes to its parent element.
Then the execution passes to its parent element and so on till the body element.
How to stop that?