-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfreecodecamp.js
3474 lines (2984 loc) · 90.6 KB
/
freecodecamp.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
// freeCodeCamp
// Basic JavaScript (110 items)
// https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/
// Glossary
/**
* backslash \
* forward slash /
* single quotes '
* double quotes "
* backquote/backtick `
*
*/
// Comment Your JavaScript Code
// comment
/*
comment
*/
/**
* comment
*/
console.log(``);
// Declare JavaScript Variables
/** data types (seven data types):
*
* undefined
* null
* boolean
* string
* symbol
* number
* object
*
* */
/**
* Variables are a simple name to represent the data we want to refer to.
*/
// declare a variable: (but may not contain spaces or start with a number.)
var ourName;
var myName;
console.log(myName); // expect output: undefined
console.log(``);
// Storing Values with the Assignment Operator
/**
* assignment operator > "=" (equals sign or equality sign)
*/
myVariable = 5; // This assigns the Number value 5 to myVariable.
myVar = 5;
console.log(myVar); // expect output: 5
myNum = myVar;
console.log(myNum); // expect output: 5
console.log(``);
// Initializing Variables with the Assignment Operator
/**
* "initialize a variable:"
* var myVar = 0;
*/
var myVar = 0;
console.log(myVar); // expect output: 0
console.log(``);
// Understanding Uninitialized Variables
/**
* If you do a mathematical operation on an undefined variable
* your result will be NaN which means "Not a Number".
*/
var a = 5;
var b = 10;
var c = "I am a";
// Understanding Case Sensitivity in Variables
/**
* In JavaScript all variables and function names are case sensitive.
* MYVAR is not the same as MyVar nor myvar.
*
* camelCase
* snake_case
* Pascal (Pascal case)
*
* Best Practice: Write variable names in JavaScript in camelCase.
*/
var someVariable;
var anotherVariableName;
var thisVariableNameIsSoLong;
// Add Two Numbers with JavaScript
myVar = 5 + 10; // assigned 15
// Subtract One Number from Another with JavaScript
myVar = 12 - 6; // assigned 6
// Multiply Two Numbers with JavaScript
myVar = 13 * 13; // assigned 169
// Divide One Number by Another with JavaScript
myVar = 16 / 2; // assigned 8
// Increment a Number with JavaScript
/**
* You can easily increment or add one to a variable with the ++ operator.
*
* i++;
*
* is the equivalent of
*
* i = i + 1;
*
*/
let i = 1;
console.log(i); // expect output: 1
i++; // i = i + 1;
console.log(i); // expect output: 2
console.log(``);
// Arithmetic operators
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()
console.log(2 + 3 - 1); // expected output: 4
console.log((4 * 3) / 2); // 12 / 2 // expected output: 6
console.log(11 % 3 ** 2); // 11 % 9 // expected output: 2
console.log(``);
/**
* ----- Addition (+) > sum of numeric operands or string concatenation
*
* 1 + 2 // 3 > // Number + Number -> addition
* 5 + 'foo' // "5foo" > // Number + String -> concatenation
*
* ----- Subtraction (-)
*
* 3 - 5 // -2
* 'foo' - 3 // NaN (Not-A-Number)
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN)
*
* ----- Division (/)
*
* 1 / 2 // returns 0.5 in JavaScript
* 1.0 / 2.0 // returns 0.5 in JavaScript
* 2.0 / 0 // returns Infinity in JavaScript
*
* ----- Multiplication (*)
*
* 2 * 2 // 4
* -2 * 2 // -4
* 'foo' * 2 // NaN
*
* ----- Remainder (%)
*
* The remainder operator returns the remainder left over
* when one operand is divided by a second operand.
* It always takes the sign of the dividend.
*
* 12 % 5 // 2
* 15 % 9 // 6
* 5.5 % 2 // 1.5
*
* ----- Exponentiation (**)
*
* a ** b ** c is equal to a ** (b ** c)
*
* 2 ** 3 // 8
* 3 ** 2.5 // 15.588457268119896
* 2 ** 3 ** 2 // 512
* 2 ** (3 ** 2) // 512
* (2 ** 3) ** 2 // 64
* -(2 ** 2) // -4
* (-2) ** 2 // 4
*
* Note: JavaScript also has a bitwise operator ^ (logical XOR).
* ** and ^ are different
* for example:
* 2 ** 3 === 8
* when
* 2 ^ 3 === 1
* 3 ^ 2 === 1
* 2 ^ 2 === 0
* 5 ^ 5 === 0
* 6 ^ 2 === 4
* 2 ^ 6 === 4
* 6 ^ 3 === 5
*
* ----- Increment (++)
*/
// Postfix
var x = 3;
console.log(x); // 3
y = x++; // y = 3, x = 4
console.log(y); // 3
console.log(x); // 4
console.log(``);
// Prefix
var a = 2;
console.log(a); // 2
b = ++a; // a = 3, b = 3
console.log(b); // 3
console.log(a); // 3
console.log(``);
/*
* ----- Decrement (--)
*/
// Postfix
var x = 3;
console.log(x); // 3
y = x--; // y = 3, x = 2
console.log(y); // 3
console.log(x); // 2
console.log(``);
// Prefix
var a = 2;
console.log(a); // 2
b = --a; // a = 1, b = 1
console.log(b); // 1
console.log(a); // 1
console.log(``);
/**
* ----- Unary negation (-)
*
* var x = 3;
* y = -x; // y = -3, x = 3
*
* Unary negation operator can convert non-numbers into a number
* var x = "4";
* y = -x; // y = -4
*
* ----- Unary plus (+)
*
* +3 // 3
* +'3' // 3
* +'aa' // NaN
* +true // 1
* +false // 0
* +null // 0
* +function(val){ return val } // NaN
*
*/
// Decrement a Number with JavaScript
/**
* You can easily decrement or decrease a variable by one with the -- operator.
*
* i--;
*
* is the equivalent of
*
* i = i - 1;
*
*/
// Create Decimal Numbers with JavaScript
/**
* Decimal numbers (floating point numbers or floats)
*/
var ourDecimal = 5.7;
var myDecimal = 6.1;
// Multiply Two Decimals with JavaScript
var product = 2.0 * 2.5;
// Divide One Decimal by Another with JavaScript
var quotient = 4.4 / 2.0; // (quotient = 2.2)
/**
* 4 / 2 = 2 (remainder = 0)
* dividend / divisor = quotient
*
* 3 / 2 = 1 (remainder = 1)
* dividend / divisor = quotient
*/
// Finding a Remainder in JavaScript
/**
* The remainder operator % gives the remainder of the division of two numbers.
*
* 5 % 2 = 1 because
* Math.floor(5 / 2) = 2 (Quotient)
* 2 * 2 = 4
* 5 - 4 = 1 (Remainder)
*
* Usage
* In mathematics, a number can be checked to be even or odd
* by checking the remainder of the division of the number by 2.
*
* 17 % 2 = 1 (17 is Odd)
* 48 % 2 = 0 (48 is Even)
*/
// Compound Assignment With Augmented Addition
myVar = myVar + 5;
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
console.log(``);
// Compound Assignment With Augmented Subtraction
myVar = myVar - 5;
console.log(myVar); // Returns 1
myVar -= 5;
console.log(myVar); // Returns -4
console.log(``);
// Compound Assignment With Augmented Multiplication
myVar = myVar * 5;
console.log(myVar); // Returns -20
myVar *= 5;
console.log(myVar); // Returns -100
console.log(``);
// Compound Assignment With Augmented Division
myVar = myVar / 5;
console.log(myVar); // Returns -20
myVar /= 5;
console.log(myVar); // Returns -4
console.log(``);
// Declare String Variables
var myName1 = "this is a string literal (using double quotes)";
console.log(myName1); // expected output: this is a string literal (using double quotes)
var myName2 = "this is a string literal (using single quotes)";
console.log(myName2); // expected output: this is a string literal (using single quotes)
var myName3 = `this is a string literal (using backquote/backtick)`;
console.log(myName3); // expected output: this is a string literal (using backquote/backtick)
console.log(``);
// Escaping Literal Quotes in Strings
/**
* In JavaScript, you can escape a quote from considering it
* as an end of string quote by placing a backslash (\) in front of the quote.
*/
var sampleStr = 'Alan said, "Peter is learning JavaScript".';
console.log(sampleStr); // expected output: Alan said, "Peter is learning JavaScript".
console.log(``);
// Quoting Strings with Single Quotes
/**
* Single and double quotes work the same in JavaScript.
*/
doubleQuoteStr = "This is a string";
singleQuoteStr = "This is also a string";
conversation = 'Finn exclaims to Jake, "Algebraic!"';
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
console.log(goodStr); // expected output: Jake asks Finn, "Hey, let's go on an adventure?"
console.log(``);
// Escape Sequences in Strings
/**
* Code Output
* \' single quote
* \" double quote
* \\ backslash
* \n newline
* \r carriage return
* \t tab
* \b word boundary
* \f form feed
*/
var singleQuote = "single quote (')";
console.log(singleQuote); // expected output: single quote (')
var doubleQuote = 'double quote (")';
console.log(doubleQuote); // expected output: double quote (")
var backslash = "backslash (\\)";
console.log(backslash); // expected output: backslash (\)
var newline = "\nnew line (\\n)\n";
console.log(newline); // expected output:
// new line (\n)
var carriageReturn = "carriage return (\\r) \r ";
console.log(carriageReturn); // expected output: rriage return (\r)
var tab = "\ttab (\\t)";
console.log(tab); // expected output: tab (\t)
var wordBoundary = "word \bboundary (\\b)";
console.log(wordBoundary); // expected output: wordboundary (\b)
var formFeed = "\fform feed\f (\\f)";
console.log(formFeed); // expected output: form feed
// (\f)
console.log(``);
// Concatenating Strings with Plus Operator
/**
* When the + operator is used with a String value,
* it is called the concatenation operator
*/
var ourStr = "I come first. " + "I come second.";
console.log(ourStr); // expected output: I come first. I come second.
console.log(``);
// Concatenating Strings with the Plus Equals Operator
var ourStr = "I come first. ";
ourStr += "I come second.";
console.log(ourStr); // expected output: I come first. I come second.
console.log(``);
// Constructing Strings with Variables
var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
console.log(ourStr); // expected output: Hello, our name is freeCodeCamp, how are you?
console.log(``);
// Appending Variables to Strings
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
console.log(ourStr); // expected output: freeCodeCamp is awesome!
console.log(``);
// Find the Length of a String
console.log("Alan Peter".length); // expected output: 10
var firstNameLength = 0;
var firstName = "Ada";
firstNameLength = firstName.length;
console.log(firstNameLength); // expected output: 3
console.log(``);
// Use Bracket Notation to Find the First Character in a String
/**
* Bracket notation ( "[]" ) is a way to get a character at a specific index within a string.
*
* Most modern programming languages, like JavaScript, don't start counting at 1 like humans do.
* They start at 0. This is referred to as Zero-based indexing.
*/
var firstName = "Marcelo";
//0123456 // Zero-based indexing
console.log(firstName[0]); // expected output: "M"
console.log(firstName[1]); // expected output: "a"
console.log(firstName[2]); // expected output: "r"
console.log(firstName[3]); // expected output: "c"
console.log(firstName[4]); // expected output: "e"
console.log(firstName[5]); // expected output: "l"
console.log(firstName[6]); // expected output: "o"
console.log(firstName[7]); // expected output: undefined
console.log(firstName[-1]); // expected output: undefined
console.log(``);
// Understand String Immutability
/**
* In JavaScript, String values are immutable,
* which means that they cannot be altered once created.
*/
var myStr = "Bob";
myStr[0] = "J";
console.log(myStr); // expected output: Bob
var myStr = "Bob";
myStr = "Job";
console.log(myStr); // expected output: Job
console.log(``);
// Use Bracket Notation to Find the Nth Character in a String
/**
* You can also use bracket notation to get the character
* at other positions within a string.
*
* Remember that computers start counting at 0,
* so the first character is actually the zeroth character.
*/
var firstName = "Ada";
var secondLetterOfFirstName = firstName[1];
console.log(secondLetterOfFirstName); // expected output: d
console.log(``);
// Use Bracket Notation to Find the Last Character in a String
/**
* In order to get the last letter of a string,
* you can subtract one from the string's length.
*/
var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];
console.log(lastLetterOfFirstName); // expected output: a
console.log(``);
// Use Bracket Notation to Find the Nth-to-Last Character in a String
/**
* You can use the same principle we just used to retrieve the last character
* in a string to retrieve the Nth-to-last character.
*/
var firstName = "Ada";
var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];
console.log(thirdToLastLetterOfFirstName); // expected output: A
console.log(``);
// Word Blanks
/**
* In a "Mad Libs" game, you are provided sentences with some missing words,
* like nouns, verbs, adjectives and adverbs.
*
* Consider this sentence - "It was really ____, and we ____ ourselves ____".
*/
var sentence =
"It was really " +
"hot" +
", and we " +
"laughed" +
" ourselves " +
"silly" +
".";
console.log(sentence); // expected output: It was really hot, and we laughed ourselves silly.
var myNoun = "dog";
var myAdjective = "big";
var myVerb = "ran";
var myAdverb = "quickly";
var wordBlanks =
"My " +
myNoun +
" saw a " +
myAdjective +
" ball and " +
myVerb +
" " +
myAdverb +
".";
console.log(wordBlanks); // expected output: My dog saw a big ball and ran quickly.
console.log(``);
// Store Multiple Values in one Variable using JavaScript Arrays
/**
* With JavaScript array variables, we can store several pieces of data in one place.
*/
var sandwich = ["peanut butter", "jelly", "bread"];
console.log(sandwich); // expected output: [ 'peanut butter', 'jelly', 'bread' ]
var myArray = ["Marcelo", 39];
console.log(myArray); // expected output: [ 'Marcelo', 39 ]
console.log(``);
// Nest one Array within Another Array
/**
* You can also nest arrays within other arrays, like this:
* [["Bulls", 23], ["White Sox", 45]].
* This is also called a multi-dimensional array.
*/
var ourArray = [
["the universe", 42],
["everything", 101010],
];
console.log(ourArray); // expected output: [ [ 'the universe', 42 ], [ 'everything', 101010 ] ]
console.log(``);
// Access Array Data with Indexes
/**
* Like strings, arrays use zero-based indexing,
* so the first element in an array has an index of 0.
* There shouldn't be any spaces between the array name
* and the square brackets.
*/
// [ 0, 1, 2]
var array = [50, 60, 70];
console.log(array[0]); // expected output: 50
var data = array[1];
console.log(data); // expected output: 60
console.log(``);
// Modify Array Data With Indexes
/**
* Unlike strings, the entries of arrays are mutable
* and can be changed freely.
*/
var ourArray = [50, 40, 30];
ourArray[0] = 15;
console.log(ourArray); // expected output: [ 15, 40, 30 ]
console.log(``);
// Access Multi-Dimensional Arrays With Indexes
/**
* One way to think of a multi-dimensional array, is as an array of arrays.
* When you use brackets to access your array,
* the first set of brackets refers to the entries in the outer-most (the first level) array,
* and each additional pair of brackets refers to the next level of entries inside.
*/
var arr = [
[1, 2, 3],
// 0, 0, 0
// 0, 1, 2
[4, 5, 6],
// 1, 1, 1
// 0, 1, 2
[7, 8, 9],
// 2, 2, 2
// 0, 1, 2
[[10, 11, 12], 13, 14],
// 3, 3, 3 , 3, 3
// 0, 0, 0 , 1, 2
// 0, 1, 2
];
console.log(arr[3]); // expected output: [[10,11,12], 13, 14]
console.log(arr[3][0]); // expected output: [10,11,12]
console.log(arr[3][0][0]); // expected output: 10
console.log(arr[3][0][1]); // expected output: 11
console.log(arr[3][0][2]); // expected output: 12
console.log(arr[3][1]); // expected output: 13
console.log(arr[1][2]); // expected output: 6
console.log(arr[0][2]); // expected output: 3
console.log(``);
// Manipulate Arrays With push()
/**
* An easy way to append data to the end of an array is via the push() function.
*
* .push() takes one or more parameters and "pushes" them onto the end of the array.
*/
var arr = [1, 2, 3];
arr.push(4);
console.log(arr); // expected output: [ 1, 2, 3, 4 ]
var myArray = [
["John", 23],
["cat", 2],
];
myArray.push(["dog", 3]);
console.log(myArray); // expected output: [ [ 'John', 23 ], [ 'cat', 2 ], [ 'dog', 3 ] ]
console.log(``);
// Manipulate Arrays With pop()
/**
* .pop() removes the last element from an array and returns that element.
*/
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // expected output: Returns 6
console.log(threeArr); // expected output: Returns [1, 4]
console.log(``);
// Manipulate Arrays With shift()
/**
* .shift() removes the first element instead of the last.
*/
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();
console.log(removedFromOurArray); // expected output: Stimpson
console.log(ourArray); // expected output: [ 'J', [ 'cat' ] ]
console.log(``);
// Manipulate Arrays With unshift()
/**
* .unshift() works exactly like .push(), but instead of adding the element
* at the end of the array, unshift() adds the element at the beginning of the array.
*/
var ourArray = ["Stimpson", "J", "cat"];
console.log(ourArray.shift()); // expected output: Stimpson
console.log(ourArray); // expected output: [ 'J', 'cat' ]
ourArray.unshift("Happy");
console.log(ourArray); // expected output: ["Happy", "J", "cat"]
console.log(``);
// Exercise: "Shopping List"
/**
* Create a shopping list in the variable myList.
* The list should be a multi-dimensional array containing several sub-arrays.
*
* The first element in each sub-array should contain a string with the name of the item.
* The second element should be a number representing the quantity i.e.
*
* ["Chocolate Bar", 15]
*
* There should be at least 5 sub-arrays in the list.
*/
var myList = [
["Chocolate Bar", 15],
["Egg", 10],
["Milk", 1],
["Bread", 1],
["Coffee", 1],
];
console.log(myList); // expected output: [
// [ 'Chocolate Bar', 15 ],
// [ 'Egg', 10 ],
// [ 'Milk', 1 ],
// [ 'Bread', 1 ],
// [ 'Coffee', 1 ]
// ]
console.log(``);
// Write Reusable JavaScript with Functions
/**
* In JavaScript, we can divide up our code into reusable parts called functions.
*
* You can call or invoke this function by using its name followed by parentheses,
* like this: functionName();
*/
function functionName() {
console.log("Hello World"); // expected output: Hello World
}
functionName();
console.log(``);
// Passing Values to Functions with Arguments
/**
* Parameters are variables that act as placeholders for the values that
* are to be input to a function when it is called. When a function is defined,
* it is typically defined along with one or more parameters. The actual values
* that are input (or "passed") into a function when it is called are known as arguments.
*/
function functionWithArgs(a, b) {
console.log(a + b);
}
functionWithArgs(2, 2); // expected output: 4
console.log(``);
// Global Scope and Functions
/**
* In JavaScript, scope refers to the visibility of variables.
* Variables which are defined outside of a function block have Global scope.
* This means, they can be seen everywhere in your JavaScript code.
*
* Variables which are used without the var keyword
* are automatically created in the global scope.
* This can create unintended consequences elsewhere in your code
* or when running a function again.
* You should always declare your variables with var.
*/
var myGlobal = 10;
function fun1() {
oopsGlobal = 5;
}
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
console.log(fun2()); // expected output: myGlobal: 10
// undefined
console.log(``);
// Local Scope and Functions
/**
* Variables which are declared within a function,
* as well as the function parameters have local scope.
* That means, they are only visible within that function.
*/
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // expected output: "foo"
// console.log(loc); // expected output: "ReferenceError: loc is not defined"
console.log(``);
// Global vs. Local Scope in Functions
/**
* It is possible to have both local and global variables with the same name.
* When you do this, the local variable takes precedence over the global variable.
*/
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
myFun(); // expected output: "Head"
console.log(myFun()); // expected output: "Head"
console.log(someVar); // expected output: "Hat"
function myFun2() {
return someVar;
}
myFun2(); // expected output: "Hat"
console.log(myFun2()); // expected output: "Hat"
console.log(``);
// Return a Value from a Function with Return
/**
* We can pass values into a function with arguments.
* You can use a return statement to send a value back out of a function.
*/
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5);
console.log(answer); // expected output: 8
console.log(``);
// Understanding Undefined Value returned from a Function
/**
* A function can include the return statement but it does not have to.
* In the case that the function doesn't have a return statement,
* when you call it, the function processes the inner code
* but the returned value is undefined.
*/
var sum = 0;
function addSum(num) {
sum = sum + num;
}
addSum(3); // sum will be modified but returned value is undefined
console.log(addSum(3)); // expected output: undefined
console.log(``);
// Assignment with a Returned Value
/**
* If you'll recall from our discussion of Storing Values with the Assignment Operator,
* everything to the right of the equal sign is resolved before the value is assigned.
* This means we can take the return value of a function and assign it to a variable.
*/
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
processed = processArg(7);
console.log(processed); // expected output: 2
console.log(``);
// Stand in Line
/**
* In Computer Science a queue is an abstract Data Structure where items are kept in order.
* New items can be added at the back of the queue
* and old items are taken off from the front of the queue.
*/
function nextInLine(arr, item) {
item = arr.push(item);
item = arr.shift();
return item;
}
console.log(nextInLine([1, 2], 3)); // expected output: 1
console.log(``);
// Understanding Boolean Values
/**
* Another data type is the Boolean.
* Booleans may only be one of two values: true or false.
* They are basically little on-off switches, where true is "on"
* and false is "off." These two states are mutually exclusive.
*/
function welcomeToBooleans() {
return true;
}
console.log(welcomeToBooleans()); // expected output: true
function welcomeToBooleans2() {
return false;
}
console.log(welcomeToBooleans2()); // expected output: false
console.log(``);