-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1100 lines (903 loc) · 25.4 KB
/
main.js
File metadata and controls
1100 lines (903 loc) · 25.4 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
"use strict"; // Strict Mode for error detection and code structure
console.log("Hello BD!");
myName();
function myName() {
var name = "mostafa";
}
// Spread Operator ==============================
let IITStudent = ["Mostafa", "Ahmed"];
let IITTeacher = [...IITStudent, "Patuwary", "Jesmin", "Yusuf"];
let IITMembers = [...IITTeacher, ...IITStudent];
// console.log(IITMembers);
// Push method without using spread operator ======================
let iitStaff = ["Kamal", "Kalam"];
IITMembers.push(iitStaff);
console.log(IITMembers); // Push function merge in separate array but spread does not
// Rest parameter
function Summation(...numbers) {
let sum = 0;
for (let i of numbers) {
sum = sum + i;
}
console.log(sum); // Output is 45
}
Summation(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Rest parameter + more parameters
function sumRest(a, b, ...numbers) {
let sum = 0;
for (let i of numbers) {
sum = sum + i;
}
console.log(sum); // Output is 15 because a and b parameters are not calculated here
let totalSum = a + b + sum;
console.log(totalSum); // Output is 65
}
sumRest(20, 30, 1, 2, 3, 4, 5);
// Dynamic function (without function name)
var myName = function (value) {
return value;
};
console.log(myName("Mostafa"));
// ES6 Variables (var, let, const) ==================================================
var myName = "Mostafa";
myName = "Mahmud"; // Reasigned with myName
console.log(myName); // Output Mahmud
let me = "Mostafa";
me = "Mahmud"; // Reasign with me
console.log(me); // Output Mahmud
// var and let can be reasigned but const can be reasigned
const sonName = "Shams";
// sonName = "Safwaan"; // It can not be
// var can be redeclared and last value is executed but let and const can't be
var country = "Bangladesh";
var country = "USA"; // Redaclared...
console.log(country);
// let and const can not be redeclared
let num = 3;
// let num = 5; // Redeclare can not be
const name = "Shams";
// const name = "Sadia"; // Redeclare can not be
// Variable Scope (local)
function myFuncForLocalVar() {
var localName = "Javascript";
console.log(localName);
}
myFuncForLocalVar();
// Variable Scope (global)
var globalName = "ECMAScript6";
function myFunction() {
console.log(globalName);
}
myFunction();
console.log(globalName);
// Variable Hoisting (Firstly value assign then variable declare)
subName = "CSE";
console.log(subName);
var subName;
// for loop usages ======================
var i; // i for iteration
for (i = 0; i < 100; i = i + 49) {
console.log("Allah"); // 3 times printed
}
// for...of loop usages =======================
var subArray = ["CSE", "Math", "English", "Physics", "Chemistry"];
for (let subject of subArray) {
console.log(subject);
}
// Create Objects and Use their values =======================================
var myComputer = {
monitor: true,
speaker: false,
CPU_box: "black",
motherboard: "Gigabyte",
};
var myComputerPro = {
motherboard: {
processor: "core_i3",
VGA: false,
RAM: "4GB",
},
monitor: {
color: "silver",
size: "22inch",
LED: true,
},
};
console.log(`Values are ${myComputer["monitor"]} and ${myComputer["motherboard"]}`);
// Output is "Values are true and Gigabyte"
// Values from nested object
console.log(myComputerPro["monitor"]["size"]); // Output "22inch"
// for...in loop ===================================
var myPC = {
monitor: true,
speaker: false,
CPU_box: "black",
motherboard: "Gigabyte",
};
for (let props in myPC) {
console.log(props); // property name only
console.log(myPC[props]); // value only
console.log(props + ": " + myPC[props]);
}
// if...else statement =============================
if (myComputerPro["motherboard"]["processor"] == "DualCore") {
console.log("Your PC is outdated");
} else if (myComputerPro["motherboard"]["processor"] == "core_i3") {
console.log("Your PC is Okay to run");
} else if (myComputerPro["motherboard"]["processor"] == "core_i7") {
console.log("Your PC is up to date");
} else {
console.log("Not found");
}
// Functions ==============================================================
// Simple function
function mycalc() {
var x = 10;
var y = 20;
var z = x + y;
console.log(z);
}
mycalc();
// Parameterized function
function parameterizedFunction(x, y) {
var z = x + y;
console.log(z);
}
parameterizedFunction(5, 10);
// Rest Parameters (...x)
function restParameterFunc(...x) {
console.log(x); // Shows all values as array
console.log(x[5]); // 6
}
restParameterFunc(1, 2, 3, 4, 5, 6, 7, "X", "Y", "Z");
// Returning function
function returnFunc1() {
return 100;
}
function returnFunc2() {
return 200;
}
function returnFunc3() {
return returnFunc1() + returnFunc2();
}
function returnFunc4() {
return returnFunc3();
}
console.log(returnFunc3()); // Output 300
console.log(returnFunc3() + 33); // Output 333
console.log(returnFunc4()); // Output 300
// Anonymous function ================================================
var anonymousFunc = function () {
return "Mostafa";
};
console.log(anonymousFunc()); // Mostafa
let functionAnonymous = () => "Hello Mostafa";
console.log(functionAnonymous()); // Hello Mostafa
// Anonymous function with parameter
var anonymousFunction = function (x) {
return x;
};
// let anonymousFunction = (x) => {return x;}
console.log(anonymousFunction("Shams")); // Shams
// Anonymous function with rest parameter
var anonymousFunction = function (...x) {
return x;
};
console.log(anonymousFunction(1, 2, 3, 4, 5)); // all values as array
// Anonymous function can be reassigned and last function is executed
// Arrow function =========================================
var arrowFunc = () => {
console.log("Ahmed Yeasin");
};
arrowFunc();
// Arrow function with parameter
var arrowFunc = (x) => {
console.log(x);
};
arrowFunc("Mostafa");
// Arrow function with rest parameter
var arrowFunc = (...x) => {
console.log(x);
};
arrowFunc("Mostafa", 1, 2, 3);
// Arrow function with return
var arrowFunc = (...x) => {
return x;
};
console.log(1, 2, 3);
var arrowFunc = () => {
return "Mostafa";
};
console.log(arrowFunc());
// Function Constructor ==========================
function Student(name, roll, subject) {
this.studentName = name;
this.studentRoll = roll;
this.studentSubject = subject;
}
var Mostafa = new Student("Mostafa", 1, "IT");
console.log(Mostafa);
// Output is:
// Student {
// studentName: 'Mostafa',
// studentRoll: 1,
// studentSubject: 'IT'
// }
console.log(Mostafa.studentSubject); // Output "IT"
// ES6 Array ================================================================
// Simple Array
var simpleArray = ["A", "B", "C", "D", "E"];
var simpleArrayConstructor = new Array("A", "B", "C", "D", "E");
console.log(simpleArray); // [ 'A', 'B', 'C', 'D', 'E' ]
for (let a of simpleArray) {
console.log(a);
}
for (let b of simpleArrayConstructor) {
console.log(b);
}
// ES6 Multidimensional Arrays
var arrayOne = ["A", "B", "C", "D", "E"];
var arrayTwo = ["F", "G", "H", "I", "J"];
var arrayThree = ["K", "L", "M", "N", "O"];
var total = [arrayOne, arrayTwo, arrayThree];
console.log(total[1][2]); // H
console.log(total[0][3]); // D
console.log(total[2][5]); // undefined
// ES6 Array de-structuring ================================
var currencies = ["BDT", "USD", "CAD", "EUR", "JPY"];
var [a, c, , d] = currencies;
console.log(d); // EUR
var [, , c, , e] = currencies;
console.log(c); // CAD
var [a, , c, ...rest] = currencies;
console.log(rest); // [ 'EUR', 'JPY' ]
var symbols = ["৳", "$", "$", "€", "¥"];
var newArr = [...currencies, ...symbols];
// var newArr = currencies.concat(symbols); // Exactly same as newArr
console.log(newArr);
// [
// 'BDT', 'USD', 'CAD',
// 'EUR', 'JPY', '৳',
// '$', '$', '€',
// '¥'
// ]
function multiplyAndDivide(a, b) {
return [a * b, a / b];
}
const array = multiplyAndDivide(10, 5);
console.log(array); // [ 50, 2 ]
// De-structuring
const [multiply, divide, addition = "No addition"] = multiplyAndDivide(10, 5);
console.log(multiply); // 50
console.log(divide); // 2
console.log(addition);
// returns No addition as a default value but if it gets 3rd parameter on return function
// Object de-structuring
const studentOne = {
stdName: "Mostafa",
Dept: "IT",
ID: 102,
Status: "Regular",
result: {
CSE101: "A",
CSE102: "B",
},
};
const studentTwo = {
stdName: "Yeasin",
Dept: "Business",
ID: 101,
result: {
BBA101: "A+",
BBA102: "A",
},
};
const { stdName, ID } = studentOne;
console.log(stdName); // Mostafa
console.log(ID); // 102
const {
result: { BBA101 },
...restData
} = studentTwo;
console.log(BBA101); // A+
console.log(restData); // { stdName: 'Yeasin', Dept: 'Business', ID: 101 }
// Object data overriding by combining/destructuring two objects
const studentThree = {
...studentOne,
...studentTwo,
};
console.log(studentThree);
// Object de-structuring in function parameter
function showStudent(data) {
console.log(`Name is ${data.stdName}. ID is ${data.ID}`);
}
showStudent(studentTwo); // Name is Yeasin. ID is 101
function showStd({ stdName, ID, choice = "Programing" }) {
console.log(`Name is ${stdName}. ID is ${ID}. Choice is ${choice}`);
}
showStd(studentTwo); // Name is Yeasin. ID is 101. Choice is Programing
// If choice property is in the object, returns the value from the object. If not, returns value from function parameter
// Array filter()
const items = [
{
name: "PC",
price: 30000,
},
{
name: "TV",
price: 7000,
},
{
name: "AC",
price: 45000,
},
{
name: "Mobile",
price: 5500,
},
{
name: "iPod",
price: 25000,
},
];
const filteredItems = items.filter((item) => {
return item.price <= 10000;
});
console.log(filteredItems); // [ { name: 'TV', price: 7000 }, { name: 'Mobile', price: 5500 } ]
const lengthItems = items.filter((item) => {
return item.name.length > 3;
});
console.log(lengthItems); // [ { name: 'Mobile', price: 5500 }, { name: 'iPod', price: 25000 } ]
// Another example of filter()
const ints = [5, 7, 12];
const odds = ints.filter((num) => {
return num % 2 !== 0;
});
console.log(odds); // [ 5, 7 ]
// Array map()
const itemsName = items.map((item) => {
return item.name;
});
console.log(itemsName); // [ 'PC', 'TV', 'AC', 'Mobile', 'iPod' ]
const numbers = [10, 20, 30];
const squareNum = numbers.map((item) => {
return item * item;
});
console.log(squareNum); // [ 100, 400, 900 ]
// Array find()
const foundItem = items.find((item) => {
return item.name === "PC";
});
console.log(foundItem); // { name: 'PC', price: 30000 }
// Array findIndex()
const foundIndex = items.findIndex((item) => {
return item.name === "AC";
});
console.log(foundIndex); // 2
// Array forEach()
items.forEach((items) => {
console.log(`${items.name} : ${items.price}`);
});
/*
PC : 30000
TV : 7000
AC : 45000
Mobile : 5500
iPod : 25000
*/
[1, 2, 3].forEach((item, index) => {
console.log(item, index);
});
/*
1 0
2 1
3 2
*/
// Array .some()
const itemsFree = () => {
items.price = 0;
};
console.log(items.some(itemsFree)); // returns false as boolean
// This should be fixed==================
// const itemMatched = () => {
// items.name === "TV";
// };
// console.log(items.some(itemMatched));
// Another example - some()
const hasNegativeNumbers = [4, 7, -9, 0, 99, 51, -11].some((num) => {
return num < 0;
});
console.log(hasNegativeNumbers); // true
// Array .every()
const itemsAllLessPrice = () => {
items.price <= 10000;
};
console.log(items.every(itemsAllLessPrice));
// returns false as boolean because all items are not under condition
const allPositiveNumbers = [4, 7, -9, 0, 99, 51, -11].every((num) => {
return num < 0;
});
console.log(allPositiveNumbers); // false
// Array reduce()
const itemReducer = items.reduce((accumulator, items) => {
return items.price + accumulator;
}, 0);
// 0 + 30000 + 7000 + 45000 + 5500 + 25000
console.log(itemReducer); // 112500
const arraySum = [1, 2, 3, 4, 5];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4 + 5
console.log(arraySum.reduce(reducer)); // 15
// 5 + 1 + 2 + 3 + 4 + 5
console.log(arraySum.reduce(reducer, 5)); // 20
// Or use in a single line
const arrSum = [1, 2, 3, 4, 5].reduce((result, item) => {
return result + item;
}, 5);
console.log(arrSum); // 20
// Array include() determines whether an array includes a certain value or not
console.log(items.includes("TV")); // returns false as boolean
const arrInclude = arraySum.includes(7);
console.log(arrInclude); // returns false as boolean
// ES6 Map (group of data)========================================
var map = new Map();
map.set("country", "BD");
map.set("currency", "BDT");
map.set("status", "developing");
map.set("education", "mid-level");
map.set("GDP", "8+");
console.log(map.keys()); // [Map Iterator] { 'country', 'currency', 'status', 'education', 'GDP' }
console.log(map.values()); // [Map Iterator] { 'BD', 'BDT', 'developing', 'mid-level', '8+' }
// ES6 Map loop
for (let value of map.values()) {
console.log(value);
}
/*
BD
BDT
developing
mid-level
8+
*/
for (let key of map.keys()) {
console.log(key);
}
/*
country
currency
status
education
GDP
*/
// ES6 Map (delete/get/clear/has) ==================
// delete(key)
// get(key)
// has(key)
// clear()
map.delete("GDP");
for (let value of map.values()) {
console.log(value);
}
/*
BD
BDT
developing
mid-level
*/
console.log(map.get("country")); // BD
if (map.has("status")) {
console.log("Found"); // Found
} else {
console.log("Not found");
}
map.clear();
for (let value of map.values()) {
console.log(value);
}
if (map.has("status")) {
console.log("Found");
} else {
console.log("Not found"); // Not found
}
// ES6 Promises ============================================================
// Basic idea on Promise (fulfill, reject)
let myPromise = new Promise((resolve, reject) => {
let a = 1 + 2;
if (a == 4) {
resolve("Success");
} else {
reject("Failed");
}
});
myPromise
.then((message) => {
console.log("'.then()' message is " + message);
})
.catch((message) => {
console.log("'.catch()' message is " + message); // '.catch()' message is Failed
});
// Pending (setTimeout()), fulfill (resolve(), then()), reject (reject(), catch())
let learnComplete = true;
let learnJS = new Promise((resolve, reject) => {
setTimeout(() => {
if (learnComplete) {
resolve("ECMAScript learning completed");
} else {
reject("ECMAScript learning not completed");
}
}, 3 * 1000);
});
// Consuming a Promise: then, catch, finally methods
function startLearn() {
console.log("Create an account and enjoy learning!");
}
learnJS
.then((success) => {
console.log(success);
})
.catch((reason) => {
console.log(reason);
})
.finally(() => {
startLearn(); // finally() executes whether the promise is fulfilled or rejected
});
// Callback, errorCallback functions ====================================
const userJoin = true;
const userWatchingMovie = true;
function watchMoving(callback, errorCallback) {
if (userJoin && userWatchingMovie) {
callback({
name: "User joined.",
message: "Enjoy the movie :(",
});
} else if (userJoin && !userWatchingMovie) {
callback({
name: "User joined.",
message: "Just joined now but not watching movie!",
});
} else {
errorCallback("Welcome to our site...");
}
}
watchMoving(
(message) => {
console.log(message.name + " " + message.message);
},
(error) => {
console.log(error);
}
);
// Transfering callback function into Promise object ==========================
function watchMovingPromise() {
return new Promise((resolve, reject) => {
if (userJoin && userWatchingMovie) {
resolve({
name: "User joined.",
message: "Enjoy the movie :(",
});
} else if (userJoin && !userWatchingMovie) {
resolve({
name: "User joined.",
message: "Just joined now but not watching movie!",
});
} else {
reject("Welcome to our site...");
}
});
}
watchMovingPromise()
.then((message) => {
console.log(message.name + " " + message.message);
})
.catch((error) => {
console.log(error);
});
// Async/ Await function with Promise object =========================
function asyncTask(i) {
return new Promise((resolve) => resolve(i + 1));
}
async function runAsyncTasks() {
const response1 = await asyncTask(0);
const response2 = await asyncTask(response1);
const response3 = await asyncTask(response2);
return "Everything done";
}
runAsyncTasks().then((result) => console.log(result)); // "Everything done" returns when every tasks are completed
// Promise without Async ================================
function runAsyncTasksPromise() {
return asyncTask(0)
.then((response1) => {
return asyncTask(response1);
})
.then((response2) => {
return asyncTask(response2);
})
.then((response3) => {
return asyncTask(response3);
})
.then((response4) => {
return "Everything done asynchronously";
});
}
runAsyncTasksPromise().then((result) => {
console.log(result);
});
// Promise.all() ====================================
const promiseOne = Promise.resolve(11); // Promise.resolve(value)
const promiseTwo = new Promise((resolve, reject) => {
resolve("Promise two done");
});
const promiseThree = 99;
const promiseFour = new Promise((resolve, reject) => {
// One structure for setTimeout ===================
// setTimeout(() => {
// resolve("Promise four done");
// }, 500);
// Another structure =========================
// setTimeout(
// () => {
// resolve;
// },
// 500,
// "Promise four done"
// );
setTimeout(resolve, 500, "Promise four done"); // Single line structure
});
Promise.all([promiseOne, promiseTwo, promiseThree, promiseFour]).then((values) => {
console.log(values);
});
// Promise.race() ======================
const promise1 = new Promise(function (resolve, reject) {
setTimeout(resolve, 300, "one");
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "two");
});
Promise.race([promise1, promise2]).then(function (value) {
console.log(value); // Both resolve, but promiseTwo is faster and output is "two"
});
// Simple promise resolve within a given time in the async function
const timeLimit = (t) => {
return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve(`Finished within ${t}`);
// }, t);
setTimeout(resolve, t, `Finished within ${t}`); // Same as above code
});
};
timeLimit(300).then((result) => console.log(result));
// Finished within 300
Promise.all([timeLimit(100), timeLimit(200), timeLimit(300)]).then((result) =>
console.log(result)
);
// [ 'Finished within 100', 'Finished within 200', 'Finished within 300' ]
// The output is consoled as an array only after resolving all the promises chronologically
const timeSlots = [1000, 2000, 3000];
const promises = [];
// Mapping the timeSlots
timeSlots.map((duration) => {
// Pushing the pending promise to the array promises
promises.push(timeLimit(duration));
});
console.log(promises); // To check the pending status on promises
// [ Promise { "pending" }, Promise { "pending" }, Promise { "pending" } ]
// Now passing the 'promises' pending array to Promise.all
Promise.all(promises).then((result) => console.log(result));
// [
// 'Finished within 1000',
// 'Finished within 2000',
// 'Finished within 3000'
// ]
// Promise.all results after all the promises are resolved
// What happens if any of the promises is rejected?!
const timeEnd = (t) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (t === 1000) {
reject(`Rejected in ${t}`);
} else {
resolve(`Finished in ${t}`);
}
}, t);
});
};
const tValues = [500, 1000, 1500];
const promisesArray = [];
tValues.map((time) => {
promisesArray.push(timeEnd(time));
});
console.log(promisesArray);
// (node:8528) UnhandledPromiseRejectionWarning: Rejected in 1000
// (node:8528) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
// Now passing pending promisesArray to Promise.all
Promise.all(promisesArray)
.then((result) => console.log(result)) // Promise.all not resolved and because of one rejecting, all the rest of the promises fail
.catch((err) => console.log(`Error throws in ${err}`)); //Returns "Error throws in Rejected in 1000"
// To handle this error for each promise, have to return catch function inside promiseArr out of Promise.all before passing to it(Promise.all)
const promiseArr = tValues.map((time) => {
return timeEnd(time).catch((err) => err);
});
Promise.all(promiseArr)
.then((result) => console.log(result))
.catch((err) => console.log(`Error throws in ${err}`));
// [ 'Finished in 500', 'Rejected in 1000', 'Finished in 1500' ]
// try{}, catch{}, finally{}, throw - Error Handling ======================
try {
console.log("try starting...");
funcTry; // funcTry is not defined
console.log("try ended."); // It is never reached
} catch (err) {
console.log("Error found: " + err.stack); // .stack is used to find the error details
} finally {
console.log("finally always runs...");
}
console.log("This is out of tray, catch, finally and continue next...");
/*
try starting...
Error found: ReferenceError: funcTry is not defined
at Object.<anonymous> (E:\JavaScript\ES6\main.js:823:3)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
finally always runs...
This is out of tray, catch, finally and continue next...
*/
// throw statement ===============
// Example 1
function getRectArea(width, height) {
if (isNaN(width) || isNaN(height)) {
// isNaN - is Not a Number
throw "Parameter is not a number!";
}
}
try {
getRectArea(3, "A");
} catch (e) {
console.error(e);
// Parameter is not a number!
}
// Example 2
let jsonData = '{"name": "Mostafa", "age": 29, "gender": "male"}';
try {
let userJson = JSON.parse(jsonData);
if (!userJson.id) {
throw new SyntaxError("ID not found");
}
console.log(userJson);
} catch (e) {
console.log("JSON Error: " + e.message);
// JSON Error: ID not found
console.log("JSON Error: " + e.id);
// JSON Error: undefined
console.log("JSON Error: " + e.name);
// JSON Error: SyntaxError
console.log("JSON Error: " + e);
// JSON Error: SyntaxError: ID not found
}
// Immediately Invoked Function Expression (IIFE) =======================
(function () {
console.log("My favorite number is 1");
})();
// My favorite number is 1
var favNumber = (function (num = 3) {
console.log("My favorite number is " + num);
})();
// My favorite number is 3
// Always returns parameter's fixed value
var favNumber = (function (num = 3) {
console.log("My favorite number is " + num);
})(7);
// My favorite number is 7
// Returns new value through parameter although 3 is initialized
var a = 1;
(function () {
var a = 2;
console.log(a); // 2
// It can not be accessed outside the function
})();
console.log(a);
// Output is 1 because ES6 Anonymous functions are considered as local varialbes
// No need always immediately invoked function expressions in ES6
let b = 1;
{
let b = 2;
console.log(b); // 2
}
console.log(b); // 1
/* Closure - A feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables — a scope chain
*/
var myName = "Mostafa";
function printName() {
console.log(myName);
}
printName(); //Mostafa
myName = "Mahmud";
printName(); // Mahmud