-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencyclopedia.html
15867 lines (14140 loc) · 711 KB
/
encyclopedia.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
<!DOCTYPE html>
<html lang="en">
<head>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-QVVBLPJCW8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-QVVBLPJCW8');
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no" />
<meta
name="description"
content="Mathieu"
/>
<meta
property="og:title"
content="Mathieu"
/>
<meta
name="twitter:title"
content="Mathieu"
/>
<title>mathieu | learn javascript</title>
<link href="encyclopedia.css" rel="stylesheet" />
<link rel="stylesheet" href="github-dark.css" />
<link rel="icon" href="green.png" type="image/png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&family=VT323&display=swap" rel="stylesheet">
</head>
<body>
<canvas id="noise" class="noise"></canvas>
<div class="overlay">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<div class="menu-overlay">
<div class="menu-bar">
<div class="menu-content">
<a href="encyclopedia.html" class="menu-line">
<div class="menu-title one">ENCYCLOPEDIA</div>
<div class="menu-title two">[01]</div>
</a>
<a href="articles.html" class="menu-line">
<div class="menu-title one">ARTICLES</div>
<div class="menu-title two">[02]</div>
</a>
<a href="about.html" class="menu-line">
<div class="menu-title one">ABOUT</div>
<div class="menu-title two">[03]</div>
</a>
</div>
</div>
</div>
<header>
<div class="fixed-box">
<button id="darkModeButton">
<div class="circle">
<div class="half left"></div>
<div class="half right"></div>
</div>
</button>
<a href="index.html" class="center-text"><b>MATHIEU</b></a>
<button class="burger">
<div class="square-container">
<div class="square-one"></div>
<div class="square-two"></div>
</div>
</button>
</div>
</header>
<main role="main" class="main-content">
<section id="elements">
<h2>Index [166]</h2>
</section>
<div class="custom-hr">
<div class="symbol half-plus l"></div>
<div class="symbol half-plus r"></div>
</div>
<br>
<nav class="alphsort">
<div class="scroller">
<ul class="scroller-content">
<li><a href="#data-types">Data Types</a></li>
<li><a href="#variables">Variables</a></li>
<li><a href="#conditionals">Conditionals</a></li>
<li><a href="#ao">Arithmetic Operators</a></li>
<li><a href="#functions">Functions</a></li>
<li><a href="#scope">Scope</a></li>
<li><a href="#arrays">Arrays</a></li>
<li><a href="#array-access">Array Inspection</a></li>
<li><a href="#array-transformation">Array Transformation</a></li>
<li><a href="#array-iteration">Array Iteration</a></li>
<li><a href="#array-mutation">Array Mutation</a></li>
<li><a href="#array-utility">Array Utility</a></li>
<li><a href="#loops">Loops</a></li>
<li><a href="#objects">Objects</a></li>
<li><a href="#dom">Document Object Model</a></li>
<li><a href="#domevents">Events</a></li>
<li><a href="#htmlforms">HTML Forms</a></li>
<li><a href="#classes">Classes</a></li>
<li><a href="#errorhandling">Error Handling</a></li>
<li><a href="#testing">Testing</a></li>
<li><a href="#comments">Comments</a></li>
</ul>
</div>
</nav>
<div id="mouse-square"></div>
<br>
<div class="custom-hr">
<div class="symbol half-plus l"></div>
<div class="symbol half-plus r"></div>
</div>
<br class="brone" />
<br class="brtwo"/>
<div class="main-container">
<div class="left-section">
<div class="left-title">
<div class="left-number">[01]</div>
<div class="left-javascript">VARIABLES</div>
</div>
<div class="left-image">
<canvas id="cubeCanvas"></canvas>
</div>
<div class="marquee-container">
<div class="marquee">
<p class="update">
// METADATA
</p>
<p class="update">
// [LAST UPDATED] 09/02/2025
</p>
<p class="update">
// [AUTHOR] MATHIEU
</p>
<p class="update">
// [LAST UPDATED] 09/02/2025
</p>
<p class="update">
// [AUTHOR] MATHIEU
</p>
<p class="update">
// METADATA
</p>
<p class="update">
// [LAST UPDATED] 09/02/2025
</p>
<p class="update">
// [AUTHOR] MATHIEU
</p>
<p class="update">
// [LAST UPDATED] 09/02/2025
</p>
<p class="update">
// [AUTHOR] MATHIEU
</p>
</div>
</div>
<div class="left-index">
<div class="navigation-title">Index [166]</div>
<div class="index-wrapper">
<div class="index-menu">
<div class="menu-item">
<input type="checkbox" id="js-checkbox" name="js-checkbox" checked>
<label for="js-checkbox">Javascript</label>
</div>
<div class="menu-item">
<input type="checkbox" id="git-checkbox" name="git-checkbox">
<label for="git-checkbox">Git</label>
</div>
<div class="menu-item">
<input type="checkbox" id="react-checkbox" name="react-checkbox">
<label for="react-checkbox">React</label>
</div>
<div class="menu-item">
<input type="checkbox" id="next-checkbox" name="next-checkbox">
<label for="next-checkbox">Next</label>
</div>
<div class="menu-item">
<input type="checkbox" id="ts-checkbox" name="ts-checkbox">
<label for="ts-checkbox">Typescript</label>
</div>
<div class="menu-item">
<input type="checkbox" id="node-checkbox" name="node-checkbox">
<label for="node-checkbox">Node</label>
</div>
</div>
<div class="indexscroller">
<div class="navigation-container">
<div class="navigationnumber">[00]</div>
<div><a href="#data-types" class="titleindex">Data Types</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[01]</div>
<div><a href="#variables" class="titleindex">Variables</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[02]</div>
<div><a href="#conditionals" class="titleindex">Conditionals</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[03]</div>
<div><a href="#ao" class="titleindex">Arithmetic Operators</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[04]</div>
<div><a href="#functions" class="titleindex">Functions</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[05]</div>
<div><a href="#scope" class="titleindex">Scope</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[06]</div>
<div><a href="#arrays" class="titleindex">Arrays</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[07]</div>
<div><a href="#array-access" class="titleindex">Array Inspection</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[08]</div>
<div><a href="#array-transformation" class="titleindex">Array Transformation</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[09]</div>
<div><a href="#array-iteration" class="titleindex">Array Iteration</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[10]</div>
<div><a href="#array-mutation" class="titleindex">Array Mutation</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[11]</div>
<div><a href="#array-utility" class="titleindex">Array Utility</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[12]</div>
<div><a href="#loops" class="titleindex">Loops</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[13]</div>
<div><a href="#objects" class="titleindex">Objects</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[14]</div>
<div><a href="#dom" class="titleindex">Document Object Model</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[15]</div>
<div><a href="#domevents" class="titleindex">Events</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[16]</div>
<div><a href="#htmlforms" class="titleindex">HTML Forms</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[17]</div>
<div><a href="#classes" class="titleindex">Classes</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[18]</div>
<div><a href="#errorhandling" class="titleindex">Error Handling</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[19]</div>
<div><a href="#testing" class="titleindex">Testing</a></div>
</div>
<div class="navigation-container">
<div class="navigationnumber">[20]</div>
<div><a href="#comments" class="titleindex">Comments</a></div>
</div>
</div>
</div>
</div>
</div>
<table class="right-section">
<tbody>
<tr>
<td id="data-types" class="tableletters" data-number="19">Data Types
<div class="tablenr">[01]</div>
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-dynamicandweak">dynamic & weak typing</td>
</tr>
<tr id="detail-tag-dynamicandweak" class="expandable-row-content">
<td>
<h3>dynamic typing</h3>
<p>In JavaScript, dynamic typing refers to the process of determining a variable’s data type during runtime, granting the developer the freedom to assign values of different types to the same variable as the program executes. When a variable is first declared, there is no requirement for it to be of a specific type, and the engine will infer the type based on the value that is eventually assigned. For instance, a variable might initially hold a numeric value, but later it can be changed to a string or even an object without causing any type errors. This flexibility allows for quick prototyping and reduces overhead in declaring and managing types, but it also places the burden of caution on the developer because inadvertent changes in variable types can lead to unpredictable behavior and debugging challenges.</p>
<br>
<h4><u>Specifications</u></h4>
<pre>
<code class="language-js">
// Example 1: Changing a variable from a number to a string
let dataPoint = 42;
console.log(typeof dataPoint); // "number"
dataPoint = "Now I'm a string!";
console.log(typeof dataPoint); // "string"
// Example 2: Changing a variable from a string to a boolean
let message = "Hello";
console.log(typeof messageOrStatus); // "string"
messageOrStatus = false;
console.log(typeof messageOrStatus); // "boolean"
// Example 3: Changing a variable from an object to an array
let person = { name: "Alice" };
console.log(typeof personOrTeam); // "object"
personOrTeam = ["Bob", "Carol"];
console.log(typeof personOrTeam); // "object" (arrays are still "object" type)
// Example 4: Reassigning types within a loop
let dynamicValue = 10;
console.log(typeof dynamicValue); // "number"
for (let i = 0; i < 2; i++) {
if (i === 1) {
dynamicValue = "Swapped to a string";
}
console.log(dynamicValue, typeof dynamicValue);
}
// Example 5: Returning different types from a function based on a condition
function getDynamicValue(flag) {
if (flag) {
return 100;
} else {
return "No value here";
}
}
let returnValue = getDynamicValue(true);
console.log(returnValue, typeof returnValue); // "number"
returnValue = getDynamicValue(false);
console.log(returnValue, typeof returnValue); // "string"
</code></pre>
<br />
<h3>weak typing</h3>
<p>Weak typing in JavaScript refers to the language’s tendency to automatically and implicitly convert values between different data types, often referred to as type coercion, whenever it deems it necessary for an operation to proceed. For example, when an expression involves both a string and a number, JavaScript may convert the number to a string (as in the case of `'5' + 2` resulting in `'52'`), or convert the string to a number (as in the case of `'5' - 2` yielding `3`). This behavior can sometimes make code concise by reducing the need for explicit conversions, but it also has the potential to produce unexpected outcomes if the developer is not fully aware of how these implicit transformations are performed. Consequently, it is critical to understand JavaScript’s rules for converting values in expressions such as comparisons, arithmetic, and concatenation, as well as being mindful when using the loose equality operator (`==`) instead of the strict equality operator (`===`), since the former will trigger type coercion while the latter will not.</p>
<br>
<h4><u>Specifications</u></h4>
<pre>
<code class="language-js">
// Example 1: Automatic conversion from number to string during concatenation
let concatenatedStringAndNumber = "5" + 2;
console.log(concatenatedStringAndNumber); // "52"
// Example 2: Automatic conversion from string to number during subtraction
let subtractedStringAndNumber = "5" - 2;
console.log(subtractedStringAndNumber); // 3
// Example 3: Coercion in comparison, where a string is treated as a number
let stringGreaterThanNumber = "10" > 9;
console.log(stringGreaterThanNumber); // true
// Example 4: Loose equality triggers type coercion (0 is coerced to false)
let zeroEqualsFalse = (0 == false);
console.log(zeroEqualsFalse); // true
// Example 5: Loose equality between a string and a number
let stringLooseEqualsNumber = ("5" == 5);
console.log(stringLooseEqualsNumber); // true
// Example 6: String + boolean becomes a concatenated string
let stringPlusBoolean = "Hello" + true;
console.log(stringPlusBoolean); // "Hellotrue"
// Example 7: Subtraction between a string and a boolean (boolean becomes a number: true -> 1)
let stringMinusBoolean = "5" - true;
console.log(stringMinusBoolean); // 4
// Example 8: Multiplication between string representations of numbers
let multipliedStrings = "6" * "3";
console.log(multipliedStrings); // 18
// Example 9: Coercion of null to 0 in arithmetic
let nullInArithmetic = null + 10;
console.log(nullInArithmetic); // 10
// Example 10: NaN result when a string cannot be coerced to a valid number
let invalidStringSubtraction = "Hello" - 2;
console.log(invalidStringSubtraction); // NaN
</code></pre>
<br />
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-data-types">primitive & non-prim. data types</td>
</tr>
<tr id="detail-tag-data-types" class="expandable-row-content">
<td>
<h3>Number</h3>
<p>Number is a fundamental primitive type in JavaScript used to represent both integers and floating-point values, including special numeric values like Infinity, -Infinity, and NaN. Since there is no separate data type for integers, numbers are stored in a double-precision 64-bit format, allowing for a wide range of values. However, because of this floating-point representation, precision issues can sometimes arise in arithmetic operations. Despite these quirks, the Number type remains central to most basic arithmetic tasks in JavaScript.</p>
<pre>
<code class="language-js">
// Example 1: A simple integer value
let userAge = 25;
console.log(userAge, typeof userAge); // 25, "number"
// Example 2: A negative integer
let temperatureInCelsius = -5;
console.log(temperatureInCelsius, typeof temperatureInCelsius); // -5, "number"
// Example 3: A floating-point number
let piApproximation = 3.14;
console.log(piApproximation, typeof piApproximation); // 3.14, "number"
// Example 4: Using scientific notation for a large number
let largeScientificNumber = 1.2e6;
console.log(largeScientificNumber, typeof largeScientificNumber); // 1200000, "number"
// Example 5: Special numeric value Infinity
let infiniteValue = Infinity;
console.log(infiniteValue, typeof infiniteValue); // Infinity, "number"
</code></pre>
<br />
<h3>BigInt</h3>
<p>BigInt is a more recent addition to JavaScript’s set of primitive types, allowing developers to work with integers of arbitrary precision. It is created by appending the letter “n” to an integer literal or by calling the BigInt constructor, enabling calculations on values larger than the maximum safe integer representable by the Number type. BigInt operations cannot be mixed freely with regular Number arithmetic without explicit conversion, making it important to decide when high-precision arithmetic is genuinely needed. Its introduction addresses a longstanding limitation for working with very large or very small integer values.</p>
<pre>
<code class="language-js">
// Example 1: Defining a very large integer using the "n" suffix
let largeCountValue = 123456789012345678901234567890n;
console.log(largeCountValue, typeof largeCountValue);
// 123456789012345678901234567890n, "bigint"
// Example 2: Creating a negative BigInt
let negativeBigIntValue = -1234567890123456789n;
console.log(negativeBigIntValue, typeof negativeBigIntValue);
// -1234567890123456789n, "bigint"
// Example 3: Constructing a BigInt from a string
let stringConstructorValue = BigInt("999999999999999999999999999999");
console.log(stringConstructorValue, typeof stringConstructorValue);
// 999999999999999999999999999999n, "bigint"
// Example 4: Performing arithmetic with BigInts
let sumOfBigInts = 5000n + 6000n;
console.log(sumOfBigInts, typeof sumOfBigInts);
// 11000n, "bigint"
// Example 5: Comparing two BigInt values
let firstBigInt = 10000n;
let secondBigInt = 9999n;
console.log(firstBigInt > secondBigInt);
// true
</code></pre>
<br />
<h3>Boolean</h3>
<p>Boolean is a simple primitive type representing only two values: true or false. These values are instrumental in controlling logic flow in JavaScript programs through conditional statements, loops, and logical operators. Booleans can also be produced by explicit comparisons, such as checking if a certain condition is met or if two values are equal. Although it is one of the smallest and most basic data types, it plays a crucial role in determining the behavior of nearly every program.</p>
<pre>
<code class="language-js">
// Example 1: A simple true value
let isUserLoggedIn = true;
console.log(isUserLoggedIn, typeof isUserLoggedIn); // true, "boolean"
// Example 2: A simple false value
let hasErrorOccurred = false;
console.log(hasErrorOccurred, typeof hasErrorOccurred); // false, "boolean"
// Example 3: Boolean resulting from a comparison
let isAgeValid = (25 > 18);
console.log(isAgeValid, typeof isAgeValid); // true, "boolean"
// Example 4: Converting a truthy value to a boolean
let userResponse = Boolean("Yes");
console.log(userResponse, typeof userResponse); // true, "boolean"
// Example 5: Checking equality in a loose comparison
let isEqual = ("100" == 100);
console.log(isEqual, typeof isEqual); // true, "boolean"
</code></pre>
<br />
<h3>String</h3>
<p>String is a primitive type that stores sequences of characters and is used extensively for representing text. In JavaScript, strings are immutable, meaning their contents cannot be altered once created, although new strings can be formed through concatenation or other operations. String literals can be denoted using single quotes, double quotes, or backticks, the latter allowing for template literals that support embedded expressions and multi-line text. Even though strings handle text data, they can also be involved in numeric-like operations due to JavaScript’s implicit type coercion, making it important to keep in mind how the language interprets these interactions.</p>
<pre>
<code class="language-js">
// Example 1: Defining a string with single quotes
let greetingMessage = 'Hello, world!';
console.log(greetingMessage, typeof greetingMessage); // "Hello, world!", "string"
// Example 2: Defining a string with double quotes
let userName = "Alice";
console.log(userName, typeof userName); // "Alice", "string"
// Example 3: Using a template literal for interpolation
let userAge = 25;
let userIntroduction = `My name is ${userName} and I am ${userAge} years old.`;
console.log(userIntroduction, typeof userIntroduction); // "My name is Alice and I am 25 years old.", "string"
// Example 4: Creating a multi-line string with backticks
let multiLineQuote = `This is line one
and this is line two.`;
console.log(multiLineQuote, typeof multiLineQuote); // (two lines of text), "string"
// Example 5: Including escape characters within a string
let filePath = "C:\\Users\\Alice\\Documents";
console.log(filePath, typeof filePath); // "C:\Users\Alice\Documents", "string"
</code></pre>
<br />
<h3>Null</h3>
<p>Null represents the intentional absence of any object value and is considered a primitive type despite the historical quirk that causes typeof null to return "object." It often serves as a way to indicate that a variable should not hold any valid data or that a requested piece of data was intentionally cleared. Because null is an actual value, assigning a variable to null is different from leaving it undefined, making it a useful marker in APIs and functions for conveying “no data.”</p>
<pre>
<code class="language-js">
// Example 1: Explicitly assigning null to a variable
let noValueAssigned = null;
console.log(noValueAssigned, typeof noValueAssigned); // null, "object"
// Example 2: Setting a variable to null after using it
let userId = 12345;
// Later, the user logs out or the ID is cleared
userId = null;
console.log(userId, typeof userId); // null, "object"
// Example 3: Returning null from a function to indicate no result
function findUser() {
// Logic determines no user is found
return null;
}
let foundUser = findUser();
console.log(foundUser, typeof foundUser); // null, "object"
// Example 4: Using null to initialize an object property
let userSettings = {
theme: null,
notifications: true
};
console.log(userSettings.theme, typeof userSettings.theme); // null, "object"
// Example 5: Placeholder null value before assigning actual data
let productDescription = null;
// Later in the code, you might replace null with an actual string
productDescription = "This is a premium product.";
console.log(productDescription); // "This is a premium product."
</code></pre>
<br />
<h3>Undefined</h3>
<p>Undefined is a primitive type that signifies a variable has been declared but has not yet been assigned a value, or that a function did not explicitly return any value. It is generally associated with uninitialized variables or missing function parameters. Although it serves a role similar to null in representing “no data,” they are conceptually different: null is an explicit assignment, while undefined naturally arises when a variable or property has no valid data bound to it yet.</p>
<pre>
<code class="language-js">
// Example 1: Declaring a variable without initializing it
let userScore;
console.log(userScore, typeof userScore); // undefined, "undefined"
// Example 2: Accessing a property that does not exist on an object
let userProfile = { name: "Alice", age: 30 };
let profileEmail = userProfile.email;
console.log(profileEmail, typeof profileEmail); // undefined, "undefined"
// Example 3: Accessing an out-of-range array index
let productList = ["Apple", "Banana", "Cherry"];
let missingProduct = productList[5];
console.log(missingProduct, typeof missingProduct); // undefined, "undefined"
// Example 4: A function that does not explicitly return anything
function calculateTotal() {
let subtotal = 100;
// No return statement, so it implicitly returns undefined
}
let totalCost = calculateTotal();
console.log(totalCost, typeof totalCost); // undefined, "undefined"
// Example 5: Setting a variable to undefined (though not generally recommended)
let temporaryHolder = "Some value";
temporaryHolder = undefined;
console.log(temporaryHolder, typeof temporaryHolder); // undefined, "undefined"
</code></pre>
<br />
<h3>Symbol</h3>
<p>Symbol is a unique and immutable primitive type introduced in ECMAScript 2015 (ES6) primarily for creating unique object property keys. Each symbol has its own identity, even if multiple symbols share the same description text. Since symbols cannot be automatically converted to strings, they help avoid naming collisions and allow the creation of hidden object properties that libraries or frameworks can use internally without worrying about conflicting with user-defined property names.</p>
<pre>
<code class="language-js">
// Example 1: Creating a simple symbol with a description
let uniqueUserId = Symbol("userId");
console.log(uniqueUserId, typeof uniqueUserId);
// Symbol(userId), "symbol"
// Example 2: Creating a symbol without a description
let anonymousSymbol = Symbol();
console.log(anonymousSymbol, typeof anonymousSymbol);
// Symbol(), "symbol"
// Example 3: Using a symbol as a key in an object
let statusKey = Symbol("status");
let orderDetails = {
[statusKey]: "Pending",
orderId: 12345
};
console.log(orderDetails[statusKey]);
// "Pending"
// Example 4: Preventing property name collisions with symbols
let sharedObject = {};
let configSymbol = Symbol("config");
let debugSymbol = Symbol("debug");
sharedObject[configSymbol] = { mode: "production" };
sharedObject[debugSymbol] = { level: "verbose" };
console.log(sharedObject[configSymbol], sharedObject[debugSymbol]);
// { mode: "production" } { level: "verbose" }
// Example 5: Symbols in a function to create unique identifiers
function createUniqueTag(tagDescription) {
return Symbol(tagDescription);
}
let myUniqueTag = createUniqueTag("componentTag");
console.log(myUniqueTag, typeof myUniqueTag);
// Symbol(componentTag), "symbol"
</code></pre>
<br />
<h3>Object</h3>
<p>Object is the only non-primitive data type in JavaScript, encompassing arrays, functions, dates, and regular expressions, as well as custom objects defined by developers. Objects are mutable collections of key-value pairs, where values can be of any type, including other objects. They are compared by reference rather than by value, meaning two different objects with identical properties are not considered equal unless they reference the exact same instance. Because objects are so flexible, they form the basis of many data structures and design patterns in JavaScript.</p>
<pre>
<code class="language-js">
// Example 1: A plain object with key-value pairs
let userProfile = {
name: "Alice",
age: 30
};
console.log(userProfile, typeof userProfile);
// { name: "Alice", age: 30 }, "object"
// Example 2: An array (arrays are a type of object)
let fruitBasket = ["Apple", "Banana", "Cherry"];
console.log(fruitBasket, typeof fruitBasket);
// ["Apple", "Banana", "Cherry"], "object"
// Example 3: A function (functions are special objects in JavaScript)
function greetUser() {
console.log("Hello, user!");
}
console.log(greetUser, typeof greetUser);
// [Function: greetUser], "function"
// (though internally a function is still considered an object)
// Example 4: A built-in Date object
let currentDateTime = new Date();
console.log(currentDateTime, typeof currentDateTime);
// e.g., 2025-01-08T12:34:56.789Z, "object"
// Example 5: A regular expression object
let namePattern = /Alice/;
console.log(namePattern, typeof namePattern);
// /Alice/, "object"
</code></pre>
<br />
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-typeof">typeof operator</td>
</tr>
<tr id="detail-tag-typeof" class="expandable-row-content">
<td>
<h3>typeof operator</h3>
<p>The typeof operator in JavaScript is used to determine the type of a given value at runtime and returns the result as a string. Common return values include “number” for numeric data, “string” for text, “boolean” for true or false, “object” for objects (including arrays and many built-in objects), “function” for functions, and “undefined” for variables that have not been assigned a value. An important quirk is that typeof null also returns “object,” which is a well-known historical artifact in the language. Despite this, typeof remains a handy tool for simple type checks, letting developers verify whether a variable holds the kind of data they expect.</p>
<br>
<h4><u>Specifications</u></h4>
<pre>
<code class="language-js">
// Example 1: Checking the type of a number
let currentLevel = 42;
console.log(typeof currentLevel); // "number"
// Example 2: Checking the type of a string
let welcomeMessage = "Hello, JavaScript!";
console.log(typeof welcomeMessage); // "string"
// Example 3: Checking the type of a boolean
let isGameOver = false;
console.log(typeof isGameOver); // "boolean"
// Example 4: Checking the type of an object
let playerProfile = { name: "Alice", score: 100 };
console.log(typeof playerProfile); // "object"
// Example 5: Checking the type of an array
let itemCollection = ["sword", "shield", "potion"];
console.log(typeof itemCollection); // "object"
// Example 6: Checking the type of a function
function greetPlayer() {
return "Greetings!";
}
console.log(typeof greetPlayer); // "function"
// Example 7: Checking the type of undefined
let uninitializedValue;
console.log(typeof uninitializedValue); // "undefined"
// Example 8: Checking the type of null (historical quirk)
let emptySlot = null;
console.log(typeof emptySlot); // "object"
// Example 9: Checking the type of a symbol
let uniqueIdentifier = Symbol("id");
console.log(typeof uniqueIdentifier); // "symbol"
// Example 10: Checking the type of a BigInt
let largeNumber = 9007199254740992n;
console.log(typeof largeNumber); // "bigint"
</code></pre>
<br />
</td>
</tr>
<tr>
<td id="variables" class="tableletters" data-number="01">VARIABLES
<div class="tablenr">[02]</div>
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-let">
let
</td>
</tr>
<tr id="detail-tag-let" class="expandable-row-content">
<td>
<h3>let</h3>
<p>A variable in programming is a storage location identified by a name, which can hold data that may be modified during the execution of a program. Variables are used to store values so that these values can be used and manipulated throughout the program. They can hold different types of data, such as numbers, strings, objects, and more. Variables enable developers to write flexible and dynamic code by providing a way to reference and operate on data without hard-coding values directly into the program.
<br><br>In JavaScript, the let keyword is used to declare a variable that is block-scoped, which means it is limited to the block, statement, or expression where it is declared. This contrasts with the older var keyword, which declares a variable globally or locally to an entire function regardless of block scope. The let keyword was introduced in ECMAScript 6 (ES6) to provide better control over variable scope and to avoid issues related to variable hoisting that are associated with var.
<br><br>When you declare a variable using let, it is not hoisted to the top of its enclosing block. Instead, it is hoisted to the top of the block but not initialized, which means it cannot be accessed until the execution reaches the line of code where it is declared. This behavior is known as the "temporal dead zone" and helps prevent errors that can occur when variables are used before they are defined.
<br><br>For example, in a block, trying to access a variable declared with let before its declaration line results in a ReferenceError. Once the declaration line is reached, the variable can be accessed and used. The let keyword also prevents the redeclaration of the same variable within the same scope, providing an additional layer of error checking. Attempting to redeclare a variable with let in the same scope results in a SyntaxError, which helps to catch mistakes and enforce cleaner code practices.
<br><br>Overall, the let keyword in JavaScript provides a way to declare variables that are confined to their block scope, reducing the likelihood of errors related to variable hoisting and redeclaration, and promoting better coding practices by encouraging the use of variables only within their intended context.</p>
<h4><u>Specifications</u></h4>
<pre>
<code class="language-js">
// Example 1: Redeclaration in the same block
let x = 10;
// let x = 20; // SyntaxError: Identifier 'x' has already been declared
x = 20; // Allowed: updating the value
console.log(x); // 20
// Example 2: Redeclaration in nested blocks
let y = 30;
{
// let y = 40; // SyntaxError: Identifier 'y' has already been declared
let z = 50;
console.log(z); // 50
}
{
let y = 40; // Allowed: different block scope
console.log(y); // 40
}
console.log(y); // 30 (original y)
// Example 3: Redeclaration in a function
function redeclareLet() {
let a = 60;
// let a = 70; // SyntaxError: Identifier 'a' has already been declared
a = 70; // Allowed: updating the value
console.log(a); // 70
}
redeclareLet();
// Example 4: Redeclaration in an if block
let condition = true;
if (condition) {
let status = 'active';
// let status = 'inactive'; // SyntaxError: Identifier 'status' has already been declared
status = 'inactive'; // Allowed: updating the value
console.log(status); // 'inactive'
}
// Example 5: Block scope
{
let x = 10;
console.log(x); // 10
}
console.log(typeof x); // undefined (x is not accessible here)
// Example 6: Temporal Dead Zone
{
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 20;
console.log(y); // 20
}
// Example 7: let in a loop block
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}
// console.log(i); // ReferenceError: i is not defined (i is not accessible here)
// Example 8: Nested blocks
{
let outer = 'outer';
{
let inner = 'inner';
console.log(outer); // outer
console.log(inner); // inner
}
// console.log(inner); // ReferenceError: inner is not defined
}
// Example 9: let in functions
function testLet() {
let z = 50;
console.log(z); // 50
}
// console.log(z); // ReferenceError: z is not defined
testLet();
// Example 10: Updating let variables
let score = 10;
score += 5;
console.log(score); // 15
</code></pre>
<br />
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-const">
const
</td>
</tr>
<tr id="detail-tag-const" class="expandable-row-content">
<td>
<h3>const</h3>
<p>The `const` keyword in JavaScript is used to declare variables that are intended to be constant, meaning their values are not supposed to change after they are initialized. Similar to the `let` keyword, `const` creates block-scoped variables. This means that the variable declared with `const` is limited to the block, statement, or expression where it is defined, and cannot be accessed outside of that scope.
<br><br>When you declare a variable with `const`, it must be initialized with a value at the time of declaration. This is because `const` variables are read-only after they are assigned a value. Trying to declare a `const` variable without initializing it will result in a syntax error. Once assigned, the variable cannot be reassigned a new value, which helps enforce immutability at the variable level.
<br><br>It's important to note that while the `const` keyword prevents reassignment of the variable itself, it does not make the value immutable. For example, if the value assigned to a `const` variable is an object or an array, the contents of that object or array can still be modified. This means you can change the properties of an object or elements of an array, but you cannot reassign the variable to a different object or array.
<br><br>Using `const` for variables that should remain unchanged helps improve code reliability and readability by signaling the intent that the variable's value should not be altered. It also reduces the risk of unintended side effects caused by variable reassignment. However, because `const` is block-scoped like `let`, it can only be accessed within the block it is declared in, and it cannot be redeclared within that same block.
<br><br>In summary, the `const` keyword in JavaScript is used to declare variables with a constant value that should not be reassigned. It provides block scope similar to `let` and enforces immutability for the variable binding itself, though not necessarily for the value it holds if that value is an object or array.</p>
<h4><u>Specifications</u></h4>
<pre>
<code class="language-js">
// Example 1: Redeclaration in the same block
const a = 10;
// const a = 20; // SyntaxError: Identifier 'a' has already been declared
// a = 20; // TypeError: Assignment to constant variable
console.log(a); // 10
// Example 2: Redeclaration in nested blocks
const b = 30;
{
// const b = 40; // SyntaxError: Identifier 'b' has already been declared
const c = 50;
console.log(c); // 50
}
{
const b = 40; // Allowed: different block scope
console.log(b); // 40
}
console.log(b); // 30 (original b)
// Example 3: Redeclaration in functions
function exampleFunction() {
const d = 60;
// const d = 70; // SyntaxError: Identifier 'd' has already been declared
console.log(d); // 60
}
exampleFunction();
// Example 4: Redeclaration in if block
const condition = true;
if (condition) {
const status = 'active';
// const status = 'inactive'; // SyntaxError: Identifier 'status' has already been declared
console.log(status); // 'active'
}
// Example 5: Initializing const without assignment
// const e; // SyntaxError: Missing initializer in const declaration
// Example 6: Modifying properties of a const object
const obj = { key: 'value' };
obj.key = 'newValue'; // Allowed: modifying object properties
console.log(obj.key); // 'newValue'
// Example 7: Modifying array elements of a const array
const arr = [1, 2, 3];
arr[0] = 10; // Allowed: modifying array elements
console.log(arr[0]); // 10
// Example 8: Block scope with const
{
const f = 70;
console.log(f); // 70
}
// console.log(f); // ReferenceError: f is not defined
// Example 9: const in loops
for (const g of [1, 2, 3]) {
console.log(g); // 1, 2, 3
}
// console.log(g); // ReferenceError: g is not defined
// Example 10: const in a switch case
const h = 'A';
switch (h) {
case 'A':
const grade = 'Excellent';
console.log(grade); // 'Excellent'
break;
case 'B':
// const grade = 'Good'; // SyntaxError: Identifier 'grade' has already been declared
break;
default:
const grade = 'Unknown'; // Allowed: different block scope
console.log(grade); // 'Unknown'
}
</code></pre>
<br />
</td>
</tr>
<tr>
<td id="conditionals" class="tableletters" data-number="02">Conditionals
<div class="tablenr">[09]</div>
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-if">
if statement
</td>
</tr>
<tr id="detail-tag-if" class="expandable-row-content">
<td>
<h3>if statement</h3>
<p>In JavaScript, an if statement is a fundamental control structure used to execute a block of code only if a specified condition is true. The syntax starts with the keyword if, followed by a condition enclosed in parentheses. This condition is an expression that the JavaScript engine evaluates to either true or false. If the condition evaluates to true, the code block enclosed in curly braces {} immediately following the if statement is executed. For instance, consider the example if (temperature > 30) { console.log("It's hot outside!"); }. In this case, if the value of the variable temperature is greater than 30, the message "It's hot outside!" will be logged to the console. However, if the condition evaluates to false, the code block within the curly braces is skipped and not executed. This allows developers to control the flow of their programs by specifying actions that should only occur when certain conditions are met, making the code more dynamic and responsive to different scenarios.</p>
<h4><u>Specifications</u></h4>
<pre>
<code class="language-js">
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
let temperature = 25;
if (temperature < 0) {
console.log("It is freezing outside.");
}
let score = 85;
if (score >= 80) {
console.log("You passed the exam.");
}
let isMember = true;
if (isMember) {
console.log("Welcome, member!");
}
let name = "Alice";
if (name === "Alice") {
console.log("Hello, Alice!");
}
let balance = 1000;
if (balance >= 500) {
console.log("You have sufficient funds.");
}
let light = "green";
if (light === "green") {
console.log("You can go.");
}
let password = "securePassword123";
if (password.length >= 8) {
console.log("Password is long enough.");
}
let itemsInCart = 3;
if (itemsInCart > 0) {
console.log("Your cart is not empty.");
}
let hasAccess = false;
if (!hasAccess) {
console.log("Access denied.");
}
</code></pre>
<br />
</td>
</tr>
<tr>
<td class="clickable" data-detail-id="detail-tag-else">
else statement
</td>
</tr>
<tr id="detail-tag-else" class="expandable-row-content">
<td>
<h3>else statement</h3>
<p>In JavaScript, the `else` statement is used to define a block of code that will be executed if the condition in the preceding `if` statement evaluates to false. It acts as a fallback or default action when the specified condition is not met. When an `if` statement evaluates its condition and finds it to be false, the code inside the `else` block runs instead. This ensures that one of the two blocks of code (either the `if` block or the `else` block) will always execute, making it useful for handling alternative outcomes. For instance, in the code snippet `if (condition) { /* code if condition is true */ } else { /* code if condition is false */ }`, if `condition` evaluates to false, the program will skip the first block and execute the code within the `else` block.</p>