/
javascript-basics.js
1293 lines (917 loc) · 27.1 KB
/
javascript-basics.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
/* 1. Varibales */
var myName; // var let const
myName = "hwwn";
var state = "cool";
console.log("My name is " + myName);
state = "California";
//0-9, a-z, A-Z, _
/***************************************************************
***************************************************************/
/* 2. Data Types */
// There are 7 data types
// Boolean. true and false
var data = true;
if (data) {
console.log("Booleans rule!")
} else {
console.log("Booleans are lame.")
}
// null. is an assignment value that means “no value”
var n = null;
console.log(n * 32);
// undefined. means a variable has not been declared, or has been declared but has not yet been assigned a value
var a;
console.log(a + 2);
// Number. 42 or 3.14159.
var num = 3.6;
var ber = 6.4;
console.log(num + ber);
// String. "Hey!"
var name = "Beau";
console.log("Hi! My name is " + name);
// Symbol (new in ECMAScript 2015). A data type whose instances are unique and immutable.
var sym1 = Symbol("foo");
var sym2 = Symbol("foo");
console.log(sym1 === sym2)
console.log(String(sym1) === String(sym2))
// Object - An object is a collection of properties, and a property is an association between a name (or key) and a value.
var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
console.log(myCar.make);
/***************************************************************
***************************************************************/
/* 3. Number */
var number = 12 + 2; // + - * / %
number += 5; // += -= *= /= %=
console.log(++number)
console.log(number);
/***************************************************************
***************************************************************/
/* 4. Strings */
var myName = 'Beau';
var sentence = "He said \"Hi!\""; // He said Hi!
var sentence = 'He said "Hi!"'; // He said Hi!
/*
Code Output
\' single quote
\" double quote
\\ backslash
\n newline
\r carriage return
\t tab
\b backspace
\f form feed
*/
var fullName = 'Beau ' + 'Carnes'; // 'Beau Carnes'
var sentence2 = 'My name is ' + fullName; // 'My name is Beau Carnes'
fullName += ' is my name.'; // 'Beau Carnes is my name'
/***************************************************************
***************************************************************/
/* 5. Strings: [bracket notation] */
var firstName = "Beau";
console.log(firstName[firstName.length - 2]);
//firstName[0] = "Q";
firstName = "Quincy";
console.log(firstName);
/***************************************************************
***************************************************************/
/* 6. twenty String Methods */
var stringOne = "freeCodeCamp is the best place to learn"
var stringTwo = "frontend and backend development"
// charAt()
console.log(stringOne.charAt(1)) // "r"
// charCodeAt()
console.log(stringOne.charCodeAt(1)) // "114"
// concat()
console.log(stringOne.concat(stringTwo)) // "freeCodeCamp is the best place to learnfrontend and backend development"
// endsWith()
console.log(stringOne.endsWith("to")) // false
// fromCharCode()
console.log(String.fromCharCode(114)) // "r"
// includes()
console.log(stringTwo.includes("end")) // true
// indexOf()
console.log(stringTwo.indexOf("end")) // 5
// lastIndexOf()
console.log(stringTwo.lastIndexOf("end")) // 17
// match()
console.log(stringTwo.match(/end/g)) // ["end", "end"]
// repeat()
console.log(stringOne.repeat(3)) // "freeCodeCamp is the best place to learnfreeCodeCamp is the best place to learnfreeCodeCamp is the best place to learn"
// replace()
console.log(stringTwo.replace(/end/g, "END")) // "frontEND and backEND development"
// search()
console.log(stringTwo.search("end")) // 5
// slice()
console.log(stringTwo.slice(2, 4)) // "on"
// split()
console.log(stringOne.split(" ")) // ["freeCodeCamp", "is", "the", "best", "place", "to, "learn"]
// startsWith()
console.log(stringOne.startsWith("free")) // true
// substr()
console.log(stringTwo.substr(2, 4)) // "onte"
// substring()
console.log(stringTwo.substring(2, 4)) // "on"
// toLowerCase()
console.log(stringOne.toLowerCase()) // "freecodecamp is the best place to learn"
// toUpperCase()
console.log(stringOne.toUpperCase()) // "FREECODECAMP IS THE BEST PLACE TO LEARN"
// trim()
var stringThree = " Subscribe now! ";
console.log(stringThree.trim()) // "Subscribe now!"
/***************************************************************
***************************************************************/
/* 7. Functions */
function square(number) {
return number * number;
}
console.log(square(4));
var someVar = "Hat";
function myFun() {
var someVar = "Shoes";
console.log(someVar);
}
myFun();
console.log(someVar);
console.log(addSquares(1, 3));
function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
a = addSquares(2, 3); // returns 13
b = addSquares(3, 4); // returns 25
c = addSquares(4, 5); // returns 41
/***************************************************************
***************************************************************/
/* 8. Hoisting */
// console.log(notDeclared); // Uncaught ReferenceError: notDeclared is not defined
console.log(definedLater);
var definedLater;
definedLater = 'I am defined!'
console.log(definedLater)
console.log(definedSimulateneously);
var definedSimulateneously = 'I am defined!'
console.log(definedSimulateneously)
doSomethingElse();
function doSomethingElse(){
console.log('I did it!');
}
functionVar(); // Uncaught TypeError: functionVar is not a function
var functionVar = function(){
console.log('I did it!');
}
/***************************************************************
***************************************************************/
/* 9. Comparison Operators & If... Else */
var isFCCGreat = true;
if (isFCCGreat) {
console.log("Free Code Camp is amazing!");
} else {
console.log("Free Code Camp is horrible!");
};
// Comparison Operators: > < <= >= == !=
var age = 10;
if (age >= 18) {
console.log("You are an adult!");
} else if (age < 2) {
console.log("You are a baby!");
} else if (age < 18) {
console.log("You are a child!");
};
if (age != 18) {console.log("You are NOT eighteen.")};
/***************************************************************
***************************************************************/
/* 10. == vs === */
// == abstract equality
// === strict equality
console.log(3 == "3");
console.log(3 === "3");
console.log(true == '1');
console.log(true === '1');
console.log("This is a string." == new String("This is a string."));
console.log("This is a string." === new String("This is a string."));
/***************************************************************
***************************************************************/
/* 11. Null vs Undefined */
var test
console.log(test)
test = null
console.log(test)
console.log(typeof null)
console.log(typeof undefined)
console.log(null === undefined)
console.log(null == undefined)
console.log(null === null)
console.log(null == null)
console.log(!null)
console.log(!!null)
console.log(1 + null)
console.log(1 + undefined)
/***************************************************************
***************************************************************/
/* 12 Short-circuit Evaluation */
if ( 4 > 5 && 5 > 6 ) {
console.log("hi")
} else {
console.log("no")
}
var test = true;
var isTrue = function(){
console.log('Test is true.');
};
var isFalse = function(){
console.log('Test is false.');
};
if(test){
// isTrue();
}
( test && isTrue() );
test = false;
if(!test){
isFalse();
}
( test || isFalse());
function theSameOldFoo(name){
name = name || 'Bar' ;
console.log("My best friend's name is " + name);
}
theSameOldFoo();
theSameOldFoo('Beau');
/***************************************************************
***************************************************************/
/* 13. Ternary Operator */
// condition ? expr1 : expr2
var age = 15;
if (age >= 18) {
console.log("You are an adult!");
} else {
console.log("You are a kid");
};
console.log((age >= 18) ? "You are an adult!" : "You are a kid.");
var stop;
age > 18 ? (
console.log("OK, you can go."),
stop = false
) : (
console.log("Sorry, you are much too young!"),
stop = true
);
var firstCheck = false,
secondCheck = false,
access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
console.log(access);
/***************************************************************
***************************************************************/
/* 14. Switch Statements */
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
console.log(day)
var Animal = 'chicken';
switch (Animal) {
case 'Cow':
case 'Giraffe':
case 'Dog':
case 'Pig':
console.log('This animal will go on Noah\'s Ark.');
Break;
case 'Spoon':
console.log('A spoon is not an animal!');
break;
case 'Dinosaur':
default:
console.log('This animal will not be on the Ark.');
}
/***************************************************************
***************************************************************/
/* 15. Array Basics */
var sandwich = ["peanut butter", "jelly", "bread"];
var teams = [["Bulls", 23], ["White Sox", 45]];
console.log(sandwich[1]);
sandwich[1] = "bananas";
console.log(sandwich);
console.log(teams[1][0]);
teams[1][0] = "red socks";
console.log(teams);
sandwich.forEach(function(element) {
console.log(element);
});
/***************************************************************
***************************************************************/
/* 16. 10 Common Array Methods */
var arr = ["a", "b", "c"];
arr.push("d");
console.log(arr); // ["a", "b", "c", "d"]
console.log(arr.pop()); // d
console.log(arr);
var arr2 = ["g", "q"];
console.log(arr.concat(arr2)); // ["a", "b", "c", "g", "q"]
console.log(arr2); // ["g", "q"]
console.log(arr.join("!")); "a!b!c"
console.log(arr.reverse()); // ["c", "b", "a"]
console.log(arr); // ["c", "b", "a"]
console.log(arr.shift()); // "c"
console.log(arr); // ["b", "a"]
console.log(arr.unshift("p")); // 3
console.log(arr);
console.log(arr.slice(1,3)); // ["b", "a"]
arr.push("i");
arr.push("f");
arr.sort(arr);
console.log(arr); // ["a", "b", "f", "i", "p"]
console.log(arr.splice(2, 2, "JS Nuggets")); // ["f", "i"]
console.log(arr); // ["a", "b", "JS Nuggets", "p"]
/***************************************************************
***************************************************************/
/* 17. Copying Arrays */
var original = [true, true, undefined, false, null];
// slice
var copy1 = original.slice(0);
// spread operator
var copy2 = [...original];
console.log(copy1, copy2);
// DEEP copying
var deepArray = [["freeCodeCamp"]];
var shallowCopy = deepArray.slice(0); //not deep copy
shallowCopy[0].push("is great");
console.log(deepArray[0], shallowCopy[0])
var deepCopy = JSON.parse(JSON.stringify(deepArray)); //deep copy
deepCopy[0].push("is great");
console.log(deepArray[0], deepCopy[0])
/***************************************************************
***************************************************************/
/* 18. Random numbers & parseInt */
// console.log(Math.floor(Math.random() * 20));
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomRange(1, 9));
console.log(parseInt("11", 2));
/***************************************************************
***************************************************************/
/* 19. For Loops */
// for ([initialization]; [condition]; [final-expression]) {}
var ourArray = [];
for (var i = 0; i < 5; i++) {
if (i > 2) break;
ourArray.push(i);
}
console.log(ourArray);
var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
/***************************************************************
***************************************************************/
/* 20. While, Do While */
var n = 0;
while (n < 5) {
n++;
//if (n == 3) continue;
if (n == 3) break;
console.log("n = " + n);
}
var i = 0;
do {
i++;
console.log("i = " + i);
} while (i < 5);
// &turn_off_js=true
/***************************************************************
***************************************************************/
/* 21. for... in / for... of */
// usage
// for (variable in object) {
// statements
// }
// for (variable of object) {
// statement
// }
let person = {fname:"Beau", lname:"Carnes", arms:2};
let ar = [3, 5, 7];
ar.foo = 'hello';
let text = "";
for (let x in person) {
text += person[x];
console.log(x);
};
console.log(text);
for (let i in ar) {
console.log(i); // "0" "1" "2" "foo"
};
for (let i of ar) {
console.log(i); // "3" "5" "7"
};
/***************************************************************
***************************************************************/
/* 22. Array iteration: 8 methods */
// forEach
[1, 2, 3].forEach(function (item, index) {
console.log(item, index);
});
// map
const three = [1, 2, 3];
const doubled = three.map(function (item) {
return item * 2;
});
console.log(doubled);
// filter
const ints = [1, 2, 3];
const evens = ints.filter(function (item) {
return item % 2 === 0;
});
console.log(evens);
// reduce
const sum = [1, 2, 3].reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum)
// some
const hasNegativeNumbers = [1, 2, 3, -1, 4].some(function (item) {
return item < 0;
});
console.log(hasNegativeNumbers);
// every
const allPositiveNumbers = [1, 2, -3].every(function (item) {
return item > 0;
});
console.log(allPositiveNumbers);
// find
const objects = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
const found = objects.find(function (item) {
return item.id === 'b';
});
console.log(found);
// find index
const objects2 = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
const foundIndex = objects2.findIndex(function (item) {
return item.id === 'b';
});
console.log(foundIndex)
/***************************************************************
***************************************************************/
/* 23. Objects */
var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.color;
console.log(myCar.make);
console.log(myCar.color);
myCar["year"] = 1969;
console.log(myCar["model"])
myCar["Do I like?"] = "I hate my car.";
console.log(myCar["Do I like?"]);
function showProps(obj, objName) {
var result = "";
for (var i in obj) {
// obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
if (obj.hasOwnProperty(i)) {
result += objName + "." + i + " = " + obj[i] + "\n";
}
}
return result;
}
console.log(showProps(myCar, "myCar"));
// Creation: object initializer
var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}};
// Creation: constructor function
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car("Chevy", "Malibu", 1993);
var anothercar = new Car("Mazda", "Miata", 1990);
console.log(mycar.model);
mycar.color = "black";
console.log(mycar.color);
// Creation: Object.create
var Animal = {
type: "Invertebrates",
displayType: function() {
console.log(this.type);
}
}
var animal1 = Object.create(Animal);
animal1.displayType();
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType();
/***************************************************************
***************************************************************/
/* 24. Objects 2 */
// Using Objects for Lookups
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W"
//...
};
console.log(alpha[2]);
// Remove Object Propertises
let dishes = {
plates: 8,
cups: 10,
forks: 28,
bowls: 13
};
delete dishes.cups;
console.log(dishes);
// Testing Objects for Properties
console.log(dishes.hasOwnProperty('plates'));
console.log(dishes.hasOwnProperty('cups'));
// Accessing and Modifying Nested Objects
var ourStroage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": "a file",
"folder1": "a file",
"folder2": "secrets",
},
"bottom drawer": "soda"
};
console.log(ourStroage.cabinet["top drawer"].folder2);
console.log(ourStroage.desk.drawer);
ourStroage.cabinet["top drawer"].folder2 = "cake recipe";
console.log(ourStroage.cabinet["top drawer"].floder2);
// Generate an Array of All Object Keys
console.log(Object.keys(ourStroage));
/***************************************************************
***************************************************************/
/* 25. AJAX = Asynchronous JavaScript And XML */
{/* <h1>AJAX with JavaScript!</h1>
<p id="demo">Let AJAX change this text</p>
<button type="button" onclick="loadDoc()">Change Content</button> */}
function loadDoc() {
var xhttp = new XMLHttpRequest();
//readyState
// 0 The request is not initialized
// 1 The request has been set up
// 2 The request has been sent
// 3 The request is in process
// 4 The request is complete
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://cors-anywhere.herokuapp.com/http://carnes.cc/code/ajax_example.txt", true);
xhttp.send();
}
/*
Adding "https://cors-anywhere.herokuapp.com/" prevents the following error:
XMLHttpRequest cannot load http://carnes.cc/code/ajax_example.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access.
*/
/***************************************************************
***************************************************************/
/* 26. JSON */
// example
var myJSON = {
"name": {
"first": "Beau",
"last": "Carnes"
},
"age":33,
"skills": [ "juggling", "stiltwalking", "coding" ],
"married": true,
"superpowers": null
}
// stringify method
var stringified = JSON.stringify(myJSON);
console.log(stringified);
// parse method
var stringJSON = '{ "name":"Beau", "kids":2,"state":"Michigan"}';
var myParse = JSON.parse(stringJSON);
console.log(myParse);
/***************************************************************
***************************************************************/
// 27. Closures
function makeFunc() {
var name = "JS Nuggets";
function displayName() {
console.log(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value());
counter.increment();
counter.increment();
console.log(counter.value());
counter.decrement();
console.log(counter.value());
/***************************************************************
***************************************************************/
/* 28. this */
/* The 'this' keyword refers to the object that "owns" the JavaScript code. */
console.log(this.document === document);
console.log(this === window);
this.a = 37;
console.log(window.a);
function f1() {
'use strict';
return this;
}
console.log(f1() === window);
function add(c, d) {
return this.a + this.b + c + d;
}
var o = {a: 1, b: 3};
console.log(add.call(o, 5, 7));
console.log(add.apply(o, [10, 20]));
function f() {
return this.a;
}
var g = f.bind({a: 'unicycle'});
console.log(g());
var h = g.bind({a: 'cereal'}); // won’t work a second time
console.log(h());
var o = {a: 8, f: f, g: g, h: h};
console.log(o.f(), o.g(), o.h());
var o = {
traditionalFunc: function () {
console.log('traditionalFunc this === o?', this === o);
},
arrowFunc: () => {
console.log('arrowFunc this === o?', this === o);
console.log('arrowFunc this === window?', this === window);
}
};
o.traditionalFunc();
o.arrowFunc();
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f()); // logs 37
var o = {prop: 23};
function independent() {
return this.prop;
}
o.f = independent;
console.log(o.f());
/***************************************************************
***************************************************************/
/* 29: Promises */
/* A promise in JavaScript represents the eventual result of an asynchronous operation. */
// Basic usage
var p = new Promise(function(resolve, reject) {
// Do an async task async task and then...