-
Notifications
You must be signed in to change notification settings - Fork 0
/
Javascript.html
1050 lines (799 loc) · 28 KB
/
Javascript.html
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
<script>
// data types ; boolean, number, symbol, number, object, undefined, null, string
// variables
var myName = "Joe" // used throughout the program
myName = 8
//3 ways to declare variables in js
let ourName = "FreeCodeCamp" // only used within the scope
const pi = 3.14 // constant through out the program, can never change
//declaring and assigning variables
// end all lines with semi colon henceforth
var a; // declaring
var b = 2; //asigning
a = 7;
b = a;
console.log(a); // allows to see things in the console
// variables are case sensitive.
//good habit to use camel case
var sum = 10 + 10;
console.log(sum); // displays the value of sum
var difference = 45 - 22;
console.log(difference);
var mult = 8 * 10;
console.log(mult);
var div = 8 / 2;
console.log(div);
var inc = mult++; //increment the value of mult by 1 then assign it to inc
console.log(inc);
var dec = inc--; //decrement the value of inc by 1 then assign it to dec
console.log(dec);
var dec = 3.3; // decimal numbers
var prod = 3.3 * 3.4;
console.log(prod);
var decdiv = 4.0 / 2.0;
console.log(decdiv);
var remainder = 11 % 2; // remainder operator. also used to determine f number is even or odd
console.log(remainder);
b = 2;
b = +10; // compound addition
b -= 2 // compound subtraction
b *= 5 // compound multiplication
var name = "Joe"; //string variables
//escaping literal quotes in js
var myStr = "I am a \"double quoted\" string inside \"double quotes\"";
console.log(myStr);
// you can also start with a single quote to avoid using escapes
//if you use back ticks, you can use both single and double quotes in the same line.
// Escapes
/***
CODE OUTPUT
\' Single quote
\" Double quote
\\ backslash
\n New line
\r Carriage return
\t Tab
\b Backspace7
\f Form feed
**/
var myStr = "First line\n\t\\Second line\nThirdLine";
console.log(myStr);
var ourStr = "I come first " + "I come second"; //Concatenation
console.log(ourStr);
var theStr = "I come first ";
theStr += "I come second"; //Another way to concatenate
console.log(theStr);
var myName = "joe";
var str = "My name is " + myName + " and I am well";
console.log(str);
var anAdjective = "Tiresome, but rewarding";
var myStr = "Coding is ";
myStr += anAdjective;
console.log(myStr);
//find length of a string
var firstLength;
var firstName = "Gathekia";
firstLength = firstName.length;
console.log(firstLength);
// find first letter of a word
var firstLetter = firstName[0];
console.log(firstLetter);
//Changing strings
//Strings are immutable, you can only change the whole string
//Finding the nth string
firstLetter = firstName[3];
console.log(firstLetter);
//to find the last letter using brackets
var lastLetter = firstName[firstName.length - 1]; //subtracted 1 because Javascript starts counting from 0. Therefore, the last letter is at position 7, and the length of the string is 8.
console.log(lastLetter);
// subtract however much you want to find the nth last letter.
//Word Blaks
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
result = "The " + myAdjective + " " + myNoun + " " + myVerb + " to the store " + myAdverb;
return result;
}
console.log(wordBlanks("dog", "big", "ran", "quickly"));
//Arrays
var ourArray = [
[
[
["My name is Joe", 23, "Rose", 32.5]
], //this is a 4 dimensions array, because you access the array with the name or label of the main array, an index to indicate the second level array, another index to indicate the third level, and a final index to tag the contents of that third level array.
["My name is Vendeta", 33, "Lily", 52.5]
],
["Second line", 0, "Some text"]
]; //Can store multiple data types
console.log(JSON.stringify(ourArray[0][1][1])); //You can print out arrays
//Or you can store data from arrays in variables
var name = ourArray[0];
console.log(name);
// Nested Arrays/ Multidimensional arrays
//Store arrays in arrays
//Dedecively, the first index points to the array and the second index points to the element inside that array
var theArray = [
["The universe is great", 23],
["Kinuthia is a sleeper", 69]
];
console.log(theArray[0][1]); //points at first array, second element
console.log(theArray[1][0]); //points at second array, first element
//deducively, you can also assign the elements of the nested array to a variable
var Kinuthia = theArray[1][0];
console.log(Kinuthia);
//Accesing Arrays with indices
// modifying using indices
theArray[1][0] = "Fatman is a deeper sleeper than Kinuthia";
console.log(theArray[1][0]);
//append data to an array with push
theArray.push(["Rosebell is a lesbian", 21]);
console.log(theArray[2][0]);
console.log(JSON.stringify(theArray));
//remove from array with pop
var anArray = [
["John F", 35],
["Abraham Linclon", 16],
["George Washington", 1]
];
var exArray = anArray.pop();
console.log(exArray);
// Remove first element using shift()
var newArray = ["Joe", 21, "Rose", 21];
var exArray = newArray.shift();
console.log(newArray[0]);
console.log(exArray);
//using unshift
//Adds an element at the beginning rather than the end
newArray.unshift("Paul");
console.log(newArray[0]);
//Scope global and local
// A global scope variable is visible everywhere in the code even in functions
// using var in a function to declare a variable, sets its scope to local, meaning another function cannot see that variable.
//Not using var makes the variable global automatically
var myGlobal = 10;
function func1() {
oopsGlobal = 5; //Variable scope local
}
function func2() {
var output = "Thus, ";
if (typeof myGlobal != "undefined") {
output += "My global " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal " + oopsGlobal;
} else {
console.log("Hehe");
}
console.log(output);
}
console.log("Kwani ni kesho");
func1();
func2();
// A locally scoped variable takes precedence over a globally scoped variable
var myCloth = "T shirt";
function func4() {
var myCloth = "Sweater";
console.log(myCloth);
}
func4();
console.log(myCloth);
//returning values with return from functions
function minusSeven(num) {
return num - 7;
}
console.log(minusSeven(10)); //returns computed value after using argument, then prints it out to the console
//the default return value of a function without a return statement is undefined
//you can assign a returned value to a variable
//using queues with nextInLine function
function nextInLine(arr, item) {
arr.push(item);
return arr.shift();
}
var testArr = [1, 2, 3, 4, 5];
console.log("Before :" + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
//Boolean datatypes
function welcomeToBoolean() {
return false;
}
//if statements
function outTrueOrFalse(isItTrue) {
if (isItTrue) {
return "Yes that was true";
}
return "No, it's false";
}
function trueOrFalse(wasThatTrue) {
if (!wasThatTrue) {
return "Yes that was !true";
}
return "No, that was !false";
}
console.log(outTrueOrFalse(false));
console.log(trueOrFalse(true));
//equality operator is ==
// == converts the two elements to the same data type then checks for equality
// the strict equality operator is === , it does not convert the data types
// or operator
// != inequality operator. does type conversion
// !== strict inequality operator
// >= greater than or equal to
// <= less than or equal to
// > greater than < less than
// && logical and
//using switch statements instead of else if
function caseInSwitch(val) {
var answer = "";
switch (val) {
case 1: //uses strict equality
answer = "alpha";
break; // breaks the loop
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
break;
default: // similar to the else statement
answer = "Not applicable";
}
return answer;
}
function checkNum(val) {
switch (val) {
case 1:
case 2:
case 3:
case 4:
case 5:
return "Lower";
break;
case 6:
case 7:
case 8:
case 9:
case 10:
return "Higher";
break;
default:
return "try again!";
}
}
console.log(checkNum(1));
console.log(caseInSwitch(4));
function isLess(a, b) {
if (a > b) {
return true;
}
return false;
}
console.log(isLess(5, 10));
//an easier way to do this is
function isItLess(a, b) {
return a < b;
}
var space = isItLess(4, 1); //you can store boolean values in variables and use them
console.log(space);
console.log(isItLess(3, 7));
//you can exit early with a return statement
function capital(a, b) {
if (a < 0 || b < 0) {
return undefined; //early returning in case this condition is true
} else {
var me = Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
return me;
}
}
console.log(capital(4, 16));
console.log(capital(-1, 0));
console.log(Math.round(4.4));
var count = 0;
function cc(card) {
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
count--;
break;
}
var holdbet = "Hold";
if (count > 0) {
holdbet = "Bet";
}
return count + " " + holdbet;
}
cc(2);
cc("K");
cc("A");
console.log(cc(5));
//Objects //Name of the object is ourDog
var ourDog = { //We access objects using properties instead of indices to access values
"name": "Camper",
"legs": 4,
"Tails": 1,
"friends": ["everything!"] //the value is an array
};
//accessing objects
var nameValue = ourDog.name;
var legValue = ourDog.legs;
// we can also use brackets to access objects, when the names of properties have spaces in them
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "Water"
};
var entreeValue = testObj["an antree"];
var drinkValue = testObj['the drink'];
//we can use variables to access object properties when we assign attributes to the variables
var myChild = {
10: "Ten years old",
20: "Twenty years old",
25: "A grown up"
};
var children = 10;
console.log("Chilren are the ones below " + myChild[children]);
//object updating
ourDog.name = "Halsey";
console.log(ourDog.name);
//adding object properties
ourDog.bark = "Bow ow";
console.log(ourDog.bark);
//Adding using bbrackets
myChild[5] = "My infant";
console.log(myChild[5]);
// deleting properties
delete ourDog.tails;
delete myChild[5];
//using objects instead of switch cases
function autoLook(val) {
var lookup = {
"Alpha": "Adams",
"Bravo": "Boston",
"Charlie": "Chicago",
"Delta": "Denver"
};
var azz = val;
return lookup[azz];
}
console.log(autoLook("Alpha"));
//Checking Object properties
if (myChild.hasOwnProperty(5)) {
console.log(5);
} else {
console.log("property not found");
}
// an object has all the data types, including arrays and other objects
var myMusic = [ //array holding object
{
"artist": " Billy Joe",
"title": "Piano man",
"releaseYear": 1973,
"formats": ["CD", "MP3", "LP", "8T"], //array inside object
"gold": true
}, {
"artist": "Beau Carnes",
"title": "Cereal man",
"releaseYear": 2003,
"formats": ["Mp3", "Mp4", "Youtube Video"],
"gold": false
}
];
console.log(myMusic[0].formats[0]);
//nesting objects inside objects
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside door": {
"trunk": "jack"
}
}
};
var gloveBoxContents = myStorage.car.inside["glove box"];
console.log(gloveBoxContents);
console.log(myStorage.car["outside door"].trunk);
//therefore, to access sub objects, you can chain the dot and brackets notations.
//accessing nested arrays and objects
var myPlants = [{
type: "flowers",
list: [
"rose",
"tulip",
"dendalion"
]
}, {
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}];
//this is an array containing two objects and two sub arrays
// accessing them is the same as using nested objects
var access = myPlants[0].list[1]; //myPlants is an array thus the brackets. list is an attribute whose key value is an array thus the need to specify which vaue in that array you need to access.
console.log(access);
//Record collection
var collection = {
"2548": {
"album": "Slippery when wet",
"artist": "Bon Jovi",
"tracks": [
"Let it rock",
"You give love a bad name"
]
},
"2468": {
"album": "1999",
"artist": "Prince",
"tracks": [
"1999",
"Little Red Corvette"
]
},
"1245": {
"artist": "Robert Palmer",
"tracks": [
"L",
"Y"
]
},
"5439": {
"album": "ABBA Gold"
}
};
//An object containing other objects
// they form a record that has ids and info about the records
//Joey thinks they can be translated into a table and thus stored in a db
var collectionCopy = JSON.parse(JSON.stringify(collection)); // this creates a copy of collection before any alterations so we can always go back to it.
//We then attempt to create a function which updates these records
function updateRecords(id, prop, value) {
collection[id][prop] = value; //from 3 attempts, Joey discovers that, even though a quoted object property is stored in a variable, when accessing that property, you must follow the rules of object accessing as though the variable were the stringed property itself and thus use square brackets instead of dot reference
return collection[id][prop];
}
var updatedVal = updateRecords(2468, "album", 2000);
console.log(updatedVal);
//check up on the copy of our object
console.log(JSON.stringify(collectionCopy));
//JSON.parse is the way to copy the contents of one data structure to another.
//iterating with while loops
var myArray = [];
var i = 0;
while (i < 5) {
myArray.push(i);
i++;
}
console.log(myArray);
//For loops
var ourArray = [];
var j = 0;
for (j = 0; j < 5; j++) {
ourArray.push(j);
}
console.log(ourArray);
//for(f = 1; f<20000; f++){
//while (f%2==0){
// console.log(f);
//}}
//counting backwards
var backArray = [];
for (var i = 10; i > 0; --i) {
backArray.push(i);
}
console.log(backArray);
//iterating over an array with a for loop
var forArray = [10, 11, 12, 13];
var k = 0;
for (var q = 0; q < forArray.length; q += 1) {
k += forArray[q];
}
console.log(k);
//nesting for loops
function multiplyAll(arr) {
var product = 1;
for (i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product *= arr[i][j] // when using this compound multiplication, either declare the variable here or assign it to 1. 0 would make the whole result zero.
return product;
}
}
return "No such name, go again";
}
var theArr = [
[1, 2],
[3, 4],
[5, 6, 7]
];
var product = multiplyAll(theArr);
console.log(product);
//Iterate do while loops...
//do while must run first and then check the condition
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 5);
console.log(i, myArray);
//profile lookup
var contacts = [{
"firstname": "Akira",
"lastname": "Laine",
"number": "1234",
"likes": ["Pizza", "coding", "Brownie points"]
}, {
"firstname": "Harry",
"lastname": "Potter",
"number": "2345",
"likes": ["Hogwarts", "Magic", "Hagrid"]
}, {
"firstname": "Sherlock",
"lastname": "Holmes",
"number": "3456",
"likes": ["Mysteries", "Classical music"]
}, ];
function lookUpProfile(name, prop) {
for (var a = 0; a < contacts.length; a++) {
while (contacts[a].firstname === name) {
var b = contacts[a][prop];
return b || "no such property"; //This line must be here, in the same scope as the assigning
}
}
return "No such name, try again"; // this is the default position
}
console.log(lookUpProfile("Sherlock", "lastname"));
// Lessons from this encounter
// I have spent many attempts looking through alternate ways to solving this conundrum, and what Ive gathered is
// 1 - The hasOwnProperty is used only on objects to find their member attributes and not values.
// - Think of object properties like array indices, for example arr[2] is actually an element, therefore contacts[1].firstname is a value accessed by that attribute.
// for this reason, I used a logical sign on contacts[a].firstname and not on contacts[a].firstname.name as I had previously done many times.
//Generating random fractions
function randomFunction() {
return Math.random();
}
console.log(randomFunction());
//generate random whole numbers
var randomNo = Math.floor(Math.random() * 20); // this is supposed to be a number between 1 and 20 everytime.
//Math.floor() rounds down a number to the nearest whole number
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}
console.log(randomWholeNum());
console.log(randomNo);
//a function to calculate a random number within given range
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(randomRange(10, 15));
// we add the min because the math.random() when multiplied to a number gives numbers from 0 to that number.
//Adding that result to the minimum number thus yields a random number between the minimum and maximum values given, because the function returns random numbers in the range between the minimum and maximum numbers
// Parse int function
function convertToInt(str) {
return parseInt(str);
}
console.log(convertToInt("56"));
console.log(convertToInt("Damn"));
//Using the parseInt function with a Radix
function conToInt(str) {
return parseInt(str, 2);
}
console.log(conToInt("100101"))
//using the conditional operator ternary
//condition ? statement-if-true : statement-if-false;
function checkEqual(a, b) {
return a === b ? true : false;
//in real life though, all you need to write is
//return a === b;
}
console.log(checkEqual(1, 2));
//Using multiple ternary ops
function checkSign(num) {
return num > 0 ? "Positive" : num < 0 ? "negative" : "zero";
}
console.log(checkSign(0));
//Im gonna do one more loop with the ternary
function grade(num) {
return (num > 0 && num < 40 ? "Failed" : num > 39 && num < 50 ? "D" : num > 49 && num < 60 ? "C" : num > 59 && num < 70 ? "B" : num > 69 && num <= 100 ? "A" : "Invalid input");
}
console.log(grade(59));
// much easier than the if else
// var lets you to declare a variable twice
// let does not allow
// helps you not declare the same variable twice
//thus many people use let
//to help you catch common mistakes use strict
function catTalk() {
"use strict";
}
//once again, var declares variables globally, let constrains it within the block scope
function checkScope() {
"use strict";
let i = "function scope";
if (true) {
let i = "block scope";
console.log("i is ", i)
}
console.log("now i is", i)
}
checkScope();
//using const to declare a read only value
function printManyTimes(str) {
"use strict";
const sentence = str + " is cool";
//sentence = str + "is amazing"; this will bring forth an error
for (let r = 0; i < str.length; i += 2) {
console.log(sentence);
}
}
printManyTimes("Joe Isaac the G")
// once you declare a const variable, you cannot reassign it again
//another good practise is to name the constant variable using upper case
//mutate an array declared with const
//although you cannot reassign it, you can mutate an array manually using indices
const MUTATE = [1, 2, 3];
function edit() {
"use strict";
//s = [3, 4, 5]; This will not work, the array is read only;
MUTATE[0] = 34;
return MUTATE;
}
console.log(JSON.stringify(edit()));
//as seen above, a constant object is never really safe from mutation. You can still change the values of a code using manual mutation.
//To prevent mutation completely use object.freeze
function freezeObj() {
"use strict";
const MATH_OBJ = {
PI: 3.14
};
//to make the object immutable
Object.freeze(MATH_OBJ);
try {
MATH_OBJ.PI = 99;
} catch (ex) {
console.log(ex);
}
return MATH_OBJ.PI;
}
const PI = freezeObj();
console.log(PI);
//Using arrow functions to write concise anonymous functions
//functions can be anonymous
var magic = function() {
return new Date();
}
console.log(magic);
// when this happens they can be converted to arrow functions, which can be written quicker
var moreMagic = () => {
return new Date();
};
console.log(moreMagic);
//this is an arrow function and it's faster to write
//this is not the end, this function can be made even shorter, especially if it's returning only one value
var miracles = () => new Date();
// shortest a function can be
// arrow functions can have parameters
var myConcat = (arr1, arr2) => arr1.concat(arr2);
console.log(myConcat([1, 2], [3, 4, 5]));
//console.log(myConcat[2]); returns undefined. To make this into an array, assign the values to a new array
var fly = myConcat([1, 2], [3, 4, 5]);
console.log(fly[1]); // this is finally an array
//writting higher order arrow functions
//functions can take another function as an argument
// higher order functions include map filter and reduce
const realNumberArray = [1, 2, 4.5, 8, 12, -12, -3, 15]
var squareList = (arr) => arr.filter(num => Number.isInteger(num) && num > 0).map(x => x * x);
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
//more working with the higher order functions
//A basic explanation before diving into higher order functions would be, since our main arrow function takes the array as an argument, it then uses the higher order functions to act on the array.
//first, the filter function checks every value and applies the conditions there in (check if the numbers are positive, and returns those numbers)
// Then, the map function takes these returned values and operates on them as specified in the function.
//In the filter, num is every element in the array, but in the map function, x is all the values returned by filter
//writting higher order functions
// this involves writing default parameters
var littleArray = [1, -2, 2, 4, -9, 10]
var numTester = (arr) => arr.filter((num) => num > 0).map(x => Math.round(x * 10.5));
var realNum = numTester(littleArray);
console.log(realNum);
const increment = (function() {
return function increment(number, value = 1) {
return number + value;
};
})();
console.log(increment(5, 3));
console.log(increment(5));
//use the rest operators with function parameters
//the rest op allows you to create a function with variable number of arguments
//One way to do this is
let summ = (function() {
return function sum(a, b, c) {
var arrr = [a, b, c];
return arrr.reduce((a, b) => a + b, 0);
};
})();
console.log(summ(4, 2, 3));
//using the rest operator though
let summy = function() {
return function mami(...args) {
return args.reduce((a, b) => a + b, 0);
};
}();
console.log(summy(4, 5, 6, 8));
// the three dots are the rest operators. They can take any number of arguments and convert them to an array.
// the array is the args after the dots
//using the spread operator
let arr2 = ['Jan', 'Feb', 'March', 'Apr', 'May'];
let arr3;
(function() {
arr3 = arr2; //this does not make a copy of array 2, it equals them such that theyre the same
//using the rest operator spreads out the contents of array 2 into single values which can then be assigned to an array
arr4 = [...arr2]; //arr4 needs to be global
arr2[0] = 'Potato';
})();
console.log(arr3);
console.log(arr4);
//using destructuring assignment to assign variables from objects
var voxel = {
x: 3.6,
y: 7.4,
z: 6.54
};
var x = voxel.x;
var y = voxel.y;
var z = voxel.z;
var {
x: a,