-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPluralsight_Javascript_Core_Language_Path.js
1961 lines (1289 loc) · 51.3 KB
/
Pluralsight_Javascript_Core_Language_Path.js
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
/*
==================================================================================================================
PLURALGIHT JavaScript Core Language Path
==================================================================================================================
JavaScript: Getting Started
Mark Zamoyta (Beginner Jan 21, 2020)
JavaScript Syntax and Operators
Paul D. Sheriff (Beginner Nov 12, 2019)
JavaScript: Functions
Prateek Parekh (Beginner Nov 15, 2019)
JavaScript Arrays and Collections
Jeff Batt (Beginner Dec 31, 2019)
Working with JavaScript Modules
Jonathan Mills (Beginner Oct 8, 2019)
JavaScript Variables and Types
Barry Luijbregts (Intermediate Aug 19, 2019)
Javascript Generators and Iterators
Marques Woodson (Intermediate Dec 31, 2019)
JavaScript Promises and Async Programming
Nate Taylor (Intermediate Nov 26, 2019)
JavaScript Security: Best Practices
Marcin Hoppe (Intermediate Aug 20, 2020)
JavaScript Objects, Prototypes, and Classes
Jim Cooper (Advanced Oct 30, 2019)
*/
//#region Pluralsight: JavaScript: Getting Started
/*
==================================================================================================================
Pluralsight: JavaScript: Getting Started by Mark Zamoyta
==================================================================================================================
*/
// Basics
// <script src="./fileName.js"/> This is valid html but will not work with all browsers (older browsers)
// <script src="./fileName.js"></script> This will work with all browsers
// Javascript is canse sensitive
let price = 49.99, discounted = false, name = 'Hiking boots'
// start naming variable with "_" or "$"
console.log(price); // gives error
let price = 100;
console.log(price); // prints out: undefined
var price = 100;
// use "let" not "var"
let price = 1.1 + 1.4;
console.log(price) // 2.40000000004
let amount = Number.parseFloat("A123.45");
console.log(amount) // does not work, prints out: NaN
let amount = Number.parseFloat("123.45A");
console.log(amount) // works, prints out: 123.45
let saved;
console.log(saved); // prints out: undefined
saved = null; // used to wipe out the variable
// If you want to wipe out a variable use "null" not "undefined". This is a best practise.
// Falsy values: false, 0, '', "", null, undefined, NaN)
// Truthy values: Everything not falsy, "0" is truthy
// if (1.1 + 1.3 === 2.4) this is false 2.40000000004 !== 2.4
// if (+(1.1 + 1.3).toFixed(2)) === 2.4) this is true
// toFixed method returns string but + prefix converts string to a number
// the ternary operator
let message = (pice > 10) ? 'expensive' : 'cheap';
//function declaration
function sayHi() {
console.log("Hi there.");
}
// function expression
let fn = function() {
console.log("Hi there.");
}
// function expression alternative
let fn = function sayHi() {
console.log("Hi there.");
}
// function name sayHi is optional. Used only for debugging purposes. sayHi() will not work when called
function getCode(num) {
let code = num * 2;
// return code;
}
// getCode will return undefined if comment out return statement
// Objects and Symbols
let mySymbol = Symbol();
let person = {
name: "John",
age: 30,
partTime: false,
[mySymbol]: 'secretInformation'
}
// Passing By Value
let message = 'Hello';
function changeMessage(message) {
message = 'Hi';
}
changeMessage(message); // message is still 'Hello'
// Passing By Reference
let person = {
name: "John",
age: 30
}
function incrementAge(p) {
p.age++;
}
incrementAge(person); // age is now 31
// CSS properties may contain dash(-) like font-weight but in JS dash is not allowed so we use came case notation like fontWeight
// isArray()
const arr = ['a', 'b', 'c']
console.log(Array.isArray(arr));
// Slice()
const newArr = arr.slice(1, 2);
// newArr = ['b'] Gets from 1-indexed element to 2-indexed element without taking 2 indexed element.
// slice does not change the original array. arr stays same.
// Splice()
const newArr = arr.splice(1, 1);
// newArr = ['a', 'c'] Delets 1 element from 1-indexed element.
// Splice is also used to insert an element
arr.splice(1, 0, 'foo');
// arr = ['a', 'foo', 'b', 'c'] Delets 1 element from 1-indexed element.
// IndefOf()
const arr = ['a', 'b', 'c']
console.log(arr.indexOf('b')); // Prints out: 1
console.log(arr.indexOf('d')); // Prints out: -1
// filter()
const arr = ['a', 'b', 'c', 'd']
const set = arr.filter(function(item){
return item > 'b';
});
// set = ['c', 'd']
// find()
const values = ['a', 'bbb', 'cc', 'd']
const found = values.find(function(item){
return item.length > 1;
});
// found = ['bbb'] returns only first matched element
// forEach()
const values = ['Mesut', 'Atilla', 'Altay']
values.forEach(function(item){
console.log(item);
});
// Problem with "var"
// lets say we have 2 js files script1.js and script2.js with given order
// if we have declared str variable globally in both files second files variable will override the first one.
// This is called polluting the global scope.
// Only one global variable should be declared as best practice like shown below
app = {
productId: 1234,
username: 'johnWick',
orderNumber: 007
}
// And js files can get global variables using app.PropertyName
productId = 123;
console.log(productId); // prints out: 123
// This is being declared on the object called window. we can access it with window.ProductId
// to avoid this situation use strict mode
//#endregion
//#region Pluralsight: JavaScript Syntax and Operators
/*
==================================================================================================================
Pluralsight: JavaScript Syntax and Operators Paul D. Sheriff
==================================================================================================================
*/
// Block level scope problem with switch cases
// Switch statement is a block but each case statement is not a block
let productId = 3;
switch (productId) {
case 1:
let message = "This product is a Book";
console.log(message);
break;
case 2:
let message = "This product is a Shoes";
console.log(message);
break;
case 3:
let message = "This product is a Pen";
console.log(message);
break;
default:
let message = "This product is unknown";
console.log(message);
break;
}
// When we run code above we get "Uncaught SyntaxError: Identifier 'message' has already been declared" error.
// To solve this issue every case statement must be surrounded with {}
switch (productId) {
case 1:{
let message = "This product is a Book";
console.log(message);
break;
}
case 2:{
let message = "This product is a Shoes";
console.log(message);
break;
}
case 3:{
let message = "This product is a Pen";
console.log(message);
break;
}
default:{
let message = "This product is unknown";
console.log(message);
break;
}
}
// For in Statement
let product = {
productId: 1234,
productName: "Book",
price: 120,
getInfo: function () {
return `Product with Id=${this.productId} costs ${this.price} dollars`;
}
}
for (const key in product) {
console.log("'" + key + "'=" + product[key]);
}
// iterates over collection of properties and methods in a given object
// returns the key (property or method)
/*
'productId'=1234
'productName'=Book
'price'=120
'getInfo'=function () {
return `Product with Id=${this.productId} costs ${this.price} dollars`;
}
*/
// For of Statement
// Iterates over the values of any iterable object.
// Returns object for each iteration
let _products = [
{
productId: 101,
productName: "Book",
price: 120,
getInfo: function () {
return `Product with Id=${this.productId} costs ${this.price} dollars`;
}
},
{
productId: 102,
productName: "Shoes",
price: 550,
getInfo: function () {
return `Product with Id=${this.productId} costs ${this.price} dollars`;
}
},
{
productId: 103,
productName: "Pen",
price: 30,
getInfo: function () {
return `Product with Id=${this.productId} costs ${this.price} dollars`;
}
}
]
for (const item of _products) {
console.log(JSON.stringify(item));
}
/*
{"productId":101,"productName":"Book","price":120}
{"productId":102,"productName":"Shoes","price":550}
{"productId":103,"productName":"Pen","price":30}
*/
let productName = "Hello";
for (const char of productName) {
console.log(`${char} - `);
}
/*
H -
e -
l -
l -
o -
*/
// Labeled Statements
even:
for (let index = 1; index <= 10; index++) {
if(index % 2 == 1){
continue even;
}
console.log(index);
}
/*
2
4
6
8
10
*/
// Its not recommended to use labels, goto.
// Strict Mode
/*
- Strict mode can be used by writing 'use strict' keyword on top of the code or inside a function block or etc.
- It can be ignored by older browsers.
- Strict mode forces all variables to be declared.
- Mistyped variable names are created globally scoped if strict is not used.
*/
function sayHi() {
'use strict';
message = 'Hey there';
console.log(message);
}
sayHi(); // Uncaught ReferenceError: message is not defined
// When strict mode is activated below statements can not be executed
// Cant use reserved words as variable names
let eval = 'Eval';
// Cant delete functions
delete sayHi();
// Cant delete variables
delete message;
// Short Circuiting
let result = isColorRed('Black') && isGreaterThan1400(1401);
function isColorRed(color) {
return color === 'Red';
}
function isGreaterThan1400(num) {
return num > 1400;
}
// Since the first expression (isColorRed('Black')) returns false second function never runs.
// Try Catch Blocks
function simpleTryCatchDemo() {
let result;
try {
console.log("This line will always be executed.");
result = num / 10;
console.log("If error occurs this line will not be executed");
} catch (error) {
console.log(erros.message);
}
finally{
console.log("Finally block will always be executed.");
}
}
simpleTryCatchDemo(); // prints out: num is not defined
// a Javascript error always has "message" and "name" properties
// Throwing custom error messages
function throwErrorDemo() {
try {
attemptDivison();
} catch (error) {
console.log(error.message + " - Error Type: " + error.name);
}
}
function attemptDivison() {
let result;
try {
result = num / 10;
} catch (error) {
throw{
"message": "An error occured inside the 'attemptDivison' function",
"name": "CustomError"
}
}
}
throwErrorDemo();
// An error occured inside the 'attemptDivison' function - Error Type: CustomError
/*
Types of built-in errors in Javascript
- ReferenceError: if non declared variable is tried to be used
- RangeError: if we overflow some range
- TypeError: if we use toUpperCase() method on numeric variables
- URIError: if a URL has invalid characters in it and if we try to decode it
- SyntaxError: if we miss single quote or double quote vs.
- EvalError : Used only for backward compatability.
*/
// Helper functions
function isArray(value) {
return value.constructor.toString().indexOf("Array") > -1;
}
function isDate(value) {
return value.constructor.toString().indexOf("Date") > -1;
}
function isNullOrUndefined(value) {
return value === null || value === undefined;
}
// instanceOf Operator
// Tests if inherits from Object (not a primitive)
let prod = new Product("Book", 500);
console.log(prod instanceof Product); // returns true
console.log(prod instanceof Object); // returns true
// instanceOf Operator does not test primitive types
let value = "Javascript";
console.log(prod instanceof String); // returns false
console.log(prod instanceof Object); // returns false
// This keyword
console.log(this.toString()); // object Window
// global window object
// This changes based onexecution context
// In a method: owner object
// In a function: global object
// In an event: element that recieved the element
// Call/apply methods: refers to object passed in
// Use strict can also affect this
console.log(this.toString()); // object Window
function foo() {
console.log(this.toString()); // object Window
}
'use strict';
console.log(this.toString()); // object Window
function foo() {
console.log(this.toString()); // gives error because this is undefined
}
/*
<button onclick="this.style.background='Red'">
In event handler
</button>
<button onclick="eventHandler(this)">
Pass to function from event handler
</button>
*/
function eventHandler(ctl) {
console.log(ctl.toString()); // object HTMLButtonElement
}
// this inside object literal always refers to property or method
// constructor function
function Book(name, price) {
this.name = name;
this.price = price;
}
// inside constructor function this reflects which object we are working with
// Spread Operator
// Spread operator expands any 'iterable' such as a string or array into an array
// IE and Edge does not support spread operator
// Converting string to an array
let productNumber = "FR-R92B-58";
let values = [...productNumber]
console.log(values); // (10) ["F", "R", "-", "R", "9", "2", "B", "-", "5", "8"]
// another use of a spread operator is copy an array
function copyArray() {
let arr = [1, 2, 4];
let arr2 =[...arr];
//Make changes on copied array
arr2.push(4);
arr2[0] = 99;
console.log(arr); // (3) [1, 2, 4]
console.log(ar2r); // (4) [99, 2, 4, 4]
}
// used for concatenating
let spProducts = [...products, ...newProducts];
// used for passing an argument
let dt = new Date(2019, 10, 15);
console.log(dt);
let dateFields = [2019, 11, 15];
let dt = new Date(...dateFields);
console.log(dt);
function multipleParams(arg1, arg2, arg3) {
console.log(arg1);
console.log(arg2);
console.log(arg3);
}
multipleParams(1,2,3);
let params = [1, 2, 3];
multipleParams(...params);
//#endregion
//#region Pluralsight: JavaScript Variables and Types
/*
==================================================================================================================
Pluralsight: JavaScript Variables and Types by Barry Luijbregts
==================================================================================================================
*/
// tagged template literal
String.raw `string text ${expression} string text
string text ${expression} \t string text`;
// escape characters are rendered as string
function getText() {
return "Hello World"
}
var str = String.raw `\t ${getText()}.`;
const arr = [1, 2, 3];
arr = "Hello"; // this is not allowed
arr[0] = 7; // this is legal
// You cant change the type but you can change the content
var arr = Object.freeze([1, 2, 3]); // this way we cant change content too
// const is used for readability
var la = getValFromDropDown(dropDown.Value);
var isEmployed = la.Factors[0];
var hasKids = la.Factors[1];
var hasLoans = la.Factors[2];
var hasCreditCards = la.Factors[3];
// destructuring syntax. Same as above
var[
isEmployed,
hasKids,
hasLoans,
hasCreditCards, // even this comma is also allowed
] = la.Factors;
// for changing array. Array deconstraction
var[
isEmployed,
hasKids,
hasLoans,
hasCreditCards,
...moreArgs
] = la.Factors;
var[a, b, c] = array;
var {Id:a, Name:b, isActive:c} = object;
var Id = Symbol(); // without new keyword
var Id = Symbol("My Id");
console.log(Id); // symbol
console.log(Id.toString()); // Symbol(MyId)
var Id1 = Symbol("My Id");
var Id2 = Symbol("My Id");
Id1 === Id2 // false
// Symbols are unique
// Where can we use symbol, we can use them when creating a property on objects
var loan = {
name: "Barry",
[Symbol("income")]: 1500
};
// when we use symbol as a property name it does not show up
console.log(Object.getOwnPropertyNames(loan)); // ["name"]
// So we can use it to create a secret property
// But this way we can see it
console.log(Object.getOwnPropertySymbols(loan)); // [Sumbol(income)]
//#endregion
//#region Pluralsight: JavaScript: Functions
/*
==================================================================================================================
Pluralsight: JavaScript: Functions by Prateek Parekh
==================================================================================================================
*/
// Function Scope
function greeting() {
let message = "Hello";
let sayHi = function hi() {
console.log(message);
}
sayHi(); // Hello
}
greeting();
function greeting() {
let message = "Hello";
let sayHi = function hi() {
let message = "Hi";
}
sayHi();
console.log(message); // Hello
}
greeting();
// Block Scope
let message = "Hello";
if (message === "Hello") {
let count = 100;
}
console.log(count); // Error
let message = "Hello";
if (message === "Hello") {
var count = 100; // global scope
}
console.log(count); // 100
let message = "Hello";
if (message === "Hello") {
let message = "Hi";
console.log(message); // Hi
}
console.log(message); // Hello
// Lexical scoping (MDN)
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
/*
init() creates a local variable called name and a function called displayName().
The displayName() function is an inner function that is defined inside init()
and is available only within the body of the init() function.
Note that the displayName() function has no local variables of its own.
However, since inner functions have access to the variables of outer functions,
displayName() can access the variable name declared in the parent function, init().
Run the code using this JSFiddle link and notice that the alert() statement within the
displayName() function successfully displays the value of the name variable,
which is declared in its parent function. This is an example of lexical scoping,
which describes how a parser resolves variable names when functions are nested.
The word lexical refers to the fact that lexical scoping uses the location where
a variable is declared within the source code to determine where that variable is available.
Nested functions have access to variables declared in their outer scope.
*/
// Immediately Invoked Function Expression (IIFE)
function greeting() {
console.log("Hello");
}
greeting(); // Hello
// same as above. has no name
(function () {
console.log("Hello");
})();
// we can assign it to avariable and use later if we want
// Closures
// MDN example
function makeFunc() {
var name = 'Mozilla';
function displayName() {
console.log(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
/*
Running this code has exactly the same effect as the previous example of the init() function above.
What's different (and interesting) is that the displayName() inner function is returned
from the outer function before being executed.
At first glance, it might seem unintuitive that this code still works. In some programming languages,
the local variables within a function exist for just the duration of that function's execution.
Once makeFunc() finishes executing, you might expect that the name variable would no longer be accessible.
However, because the code still works as expected, this is obviously not the case in JavaScript.
The reason is that functions in JavaScript form closures.
A closure is the combination of a function and the lexical environment within which that function was declared.
This environment consists of any local variables that were in-scope at the time the closure was created.
In this case, myFunc is a reference to the instance of the function displayName that is created when makeFunc is run.
The instance of displayName maintains a reference to its lexical environment, within which the variable name exists.
For this reason, when myFunc is invoked, the variable name remains available for use, and "Mozilla" is passed to alert.
*/
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
/*
In this example, we have defined a function makeAdder(x), that takes a single argument x, and returns a new function.
The function it returns takes a single argument y, and returns the sum of x and y.
In essence, makeAdder is a function factory. It creates functions that can add a specific value to their argument.
In the above example, the function factory creates two new functions—one that adds five to its argument, and one that adds 10.
add5 and add10 are both closures. They share the same function body definition, but store different lexical environments.
In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
*/
let greeting = (function (){
let message = "Hello";
let getMessage = function (){
return message;
};
})();
console.log(greeting.message); // undefined
let greeting = (function (){
let message = "Hello";
let getMessage = function (){
return message;
};
return{