This repository has been archived by the owner on May 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 960
/
questions.json
1999 lines (1999 loc) · 156 KB
/
questions.json
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
[
{
"name": "accessibility-aria.md",
"question": "What is ARIA and when should you use it?",
"answer": "ARIA stands for \"Accessible Rich Internet Applications\", and is a technical specification created by the World Wide Web Consortium (W3C). Better known as WAI-ARIA, it provides additional HTML attributes in the development of web applications to offer people who use assistive technologies (AT) a more robust and interoperable experience with dynamic components. By providing the component's role, name, and state, AT users can better understand how to interact with the component. WAI-ARIA should only be used when an HTML element equivalent is not available or lacks full browser or AT support. WAI-ARIA's semantic markup coupled with JavaScript works to provide an understandable and interactive experience for people who use AT.\n\nAn example using ARIA:\n\n```\n<div \n role=\"combobox\"\n aria-expanded=\"false\"\n aria-owns=\"ex1-grid\"\n aria-haspopup=\"grid\"\n id=\"ex1-combobox\">\n ...\n</div>\n```\nCredit: W3C's [ARIA 1.1 Combobox with Grid Popup Example](https://w3c.github.io/aria-practices/examples/combobox/aria1.1pattern/grid-combo.html)",
"goodToHear": [
"Accessible Rich Internet Applications",
"Benefits people who use assistive technologies (AT)",
"Provides role, name, and state",
"Semantic HTML coupled with JavaScript"
],
"links": [
"[WAI-ARIA Overview](https://www.w3.org/WAI/standards-guidelines/aria/)",
"[WAI-ARIA Spec](https://www.w3.org/TR/wai-aria/)",
"[ARIA Serious? Eric Eggert presentation](https://youtu.be/4bH57rWPnYo)"
],
"tags": [
"accessibility"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```\n<div \n role=\"combobox\"\n aria-expanded=\"false\"\n aria-owns=\"ex1-grid\"\n aria-haspopup=\"grid\"\n id=\"ex1-combobox\">\n ...\n</div>\n```"
]
},
{
"name": "accessibility-tree.md",
"question": "What is the Accessibility Tree?",
"answer": "The Accessibility Tree is a structure produced by the browser's Accessibility APIs which provides accessibility information to assistive technologies such as screen readers. \nIt runs parallel to the DOM and is similar to the DOM API, but with much fewer nodes, because a lot of that information is only useful for visual presentation. \nBy writing semantic HTML we can take advantage of this process in creating an accessible experience for our users.",
"goodToHear": [
"Tree structure exposing information to assistive technologies",
"Runs parallel to the DOM",
"Semantic HTML is essential in creating accessible experiences"
],
"links": [
"[Accessibility APIs](https://www.smashingmagazine.com/2015/03/web-accessibility-with-accessibility-api/)"
],
"tags": [
"accessibility"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "alt-attribute.md",
"question": "What is the purpose of the `alt` attribute on images?",
"answer": "The `alt` attribute provides alternative information for an image if a user cannot view it. The `alt` attribute should be used to describe any images except those which only serve a decorative purpose, in which case it should be left empty.",
"goodToHear": [
"Decorative images should have an empty `alt` attribute.",
"Web crawlers use `alt` tags to understand image content, so they are considered important for Search Engine Optimization (SEO).",
"Put the `.` at the end of `alt` tag to improve accessibility."
],
"links": [
"[A good basis for accessibility](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML)"
],
"tags": [
"html"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "async-defer-attributes.md",
"question": "What are `defer` and `async` attributes on a `<script>` tag?",
"answer": "If neither attribute is present, the script is downloaded and executed synchronously, and will halt parsing of the document until it has finished executing (default behavior). Scripts are downloaded and executed in the order\nthey are encountered.\n\nThe `defer` attribute downloads the script while the document is still parsing but waits until the document has finished parsing before executing it, equivalent to executing inside a `DOMContentLoaded` event listener. `defer` scripts will execute in order.\n\nThe `async` attribute downloads the script during parsing the document but will pause the parser to execute the script before it has fully finished parsing. `async` scripts will not necessarily execute in order.\n\nNote: both attributes must only be used if the script has a `src` attribute (i.e. not an inline script).\n\n```html\n<script src=\"myscript.js\"></script>\n<script src=\"myscript.js\" defer></script>\n<script src=\"myscript.js\" async></script>\n```",
"goodToHear": [
"Placing a `defer` script in the `<head>` allows the browser to download the script while the page is still parsing, and is therefore a better option than placing the script before the end of the body.",
"If the scripts rely on each other, use `defer`.",
"If the script is independent, use `async`.",
"Use `defer` if the DOM must be ready and the contents are not placed within a `DOMContentLoaded` listener."
],
"links": [
"[async vs defer attributes](http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html)"
],
"tags": [
"html"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```html\n<script src=\"myscript.js\"></script>\n<script src=\"myscript.js\" defer></script>\n<script src=\"myscript.js\" async></script>\n```"
]
},
{
"name": "batches.md",
"question": "Create a function `batches` that returns the maximum number of whole batches that can be cooked from a recipe.\n\n```js\n/**\nIt accepts two objects as arguments: the first object is the recipe\nfor the food, while the second object is the available ingredients.\nEach ingredient's value is a number representing how many units there are.\n\n`batches(recipe, available)`\n*/\n\n// 0 batches can be made\nbatches(\n { milk: 100, butter: 50, flour: 5 },\n { milk: 132, butter: 48, flour: 51 }\n)\nbatches(\n { milk: 100, flour: 4, sugar: 10, butter: 5 },\n { milk: 1288, flour: 9, sugar: 95 }\n)\n\n// 1 batch can be made\nbatches(\n { milk: 100, butter: 50, cheese: 10 },\n { milk: 198, butter: 52, cheese: 10 }\n)\n\n// 2 batches can be made\nbatches(\n { milk: 2, sugar: 40, butter: 20 },\n { milk: 5, sugar: 120, butter: 500 }\n)\n```",
"answer": "We must have all ingredients of the recipe available, and in quantities that are more than or equal to the number of units required. If just one of the ingredients is not available or lower than needed, we cannot make a single batch.\n\nUse `Object.keys()` to return the ingredients of the recipe as an array, then use `Array.prototype.map()` to map each ingredient to the ratio of available units to the amount required by the recipe. If one of the ingredients required by the recipe is not available at all, the ratio will evaluate to `NaN`, so the logical OR operator can be used to fallback to `0` in this case.\n\nUse the spread `...` operator to feed the array of all the ingredient ratios into `Math.min()` to determine the lowest ratio. Passing this entire result into `Math.floor()` rounds down to return the maximum number of whole batches.\n\n```js\nconst batches = (recipe, available) =>\n Math.floor(\n Math.min(...Object.keys(recipe).map(k => available[k] / recipe[k] || 0))\n )\n```",
"goodToHear": [],
"links": [],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [
"```js\n/**\nIt accepts two objects as arguments: the first object is the recipe\nfor the food, while the second object is the available ingredients.\nEach ingredient's value is a number representing how many units there are.\n\n`batches(recipe, available)`\n*/\n\n// 0 batches can be made\nbatches(\n { milk: 100, butter: 50, flour: 5 },\n { milk: 132, butter: 48, flour: 51 }\n)\nbatches(\n { milk: 100, flour: 4, sugar: 10, butter: 5 },\n { milk: 1288, flour: 9, sugar: 95 }\n)\n\n// 1 batch can be made\nbatches(\n { milk: 100, butter: 50, cheese: 10 },\n { milk: 198, butter: 52, cheese: 10 }\n)\n\n// 2 batches can be made\nbatches(\n { milk: 2, sugar: 40, butter: 20 },\n { milk: 5, sugar: 120, butter: 500 }\n)\n```"
],
"answerCodeBlocks": [
"```js\nconst batches = (recipe, available) =>\n Math.floor(\n Math.min(...Object.keys(recipe).map(k => available[k] / recipe[k] || 0))\n )\n```"
]
},
{
"name": "bem.md",
"question": "What is CSS BEM?",
"answer": "The BEM methodology is a naming convention for CSS classes in order to keep CSS more maintainable by defining namespaces to solve scoping issues. BEM stands for Block Element Modifier which is an explanation for its structure. A Block is a standalone component that is reusable across projects and acts as a \"namespace\" for sub components (Elements). Modifiers are used as flags when a Block or Element is in a certain state or is different in structure or style.\n\n```css\n/* block component */\n.block {\n}\n\n/* element */\n.block__element {\n}\n\n/* modifier */\n.block__element--modifier {\n}\n```\n\nHere is an example with the class names on markup:\n\n```html\n<nav class=\"navbar\">\n <a href=\"/\" class=\"navbar__link navbar__link--active\"></a>\n <a href=\"/\" class=\"navbar__link\"></a>\n <a href=\"/\" class=\"navbar__link\"></a>\n</nav>\n```\n\nIn this case, `navbar` is the Block, `navbar__link` is an Element that makes no sense outside of the `navbar` component, and `navbar__link--active` is a Modifier that indicates a different state for the `navbar__link` Element.\n\nSince Modifiers are verbose, many opt to use `is-*` flags instead as modifiers.\n\n```html\n<a href=\"/\" class=\"navbar__link is-active\"></a>\n```\n\nThese must be chained to the Element and never alone however, or there will be scope issues.\n\n```css\n.navbar__link.is-active {\n}\n```",
"goodToHear": [
"Alternative solutions to scope issues like CSS-in-JS"
],
"links": [
"[Writing clean and maintainable CSS](https://hackernoon.com/writing-clean-and-maintainable-css-using-bem-methodology-1dcbf810a664)"
],
"tags": [
"css"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```css\n/* block component */\n.block {\n}\n\n/* element */\n.block__element {\n}\n\n/* modifier */\n.block__element--modifier {\n}\n```",
"```html\n<nav class=\"navbar\">\n <a href=\"/\" class=\"navbar__link navbar__link--active\"></a>\n <a href=\"/\" class=\"navbar__link\"></a>\n <a href=\"/\" class=\"navbar__link\"></a>\n</nav>\n```",
"```html\n<a href=\"/\" class=\"navbar__link is-active\"></a>\n```",
"```css\n.navbar__link.is-active {\n}\n```"
]
},
{
"name": "big-o-notation.md",
"question": "What is Big O Notation?",
"answer": "Big O notation is used in Computer Science to describe the time complexity of an algorithm. The best algorithms will execute the fastest and have the simplest complexity.\n\nAlgorithms don't always perform the same and may vary based on the data they are supplied. While in some cases they will execute quickly, in other cases they will execute slowly, even with the same number of elements to deal with.\n\nIn these examples, the base time is 1 element = `1ms`.\n\n##### O(1)\n\n```js\narr[arr.length - 1]\n```\n\n* 1000 elements = `1ms`\n\nConstant time complexity. No matter how many elements the array has, it will theoretically take (excluding real-world variation) the same amount of time to execute.\n\n##### O(N)\n\n```js\narr.filter(fn)\n```\n\n* 1000 elements = `1000ms`\n\nLinear time complexity. The execution time will increase linearly with the number of elements the array has. If the array has 1000 elements and the function takes 1ms to execute, 7000 elements will take 7ms to execute. This is because the function must iterate through all elements of the array before returning a result.\n\n##### O([1, N])\n\n```js\narr.some(fn)\n```\n\n* 1000 elements = `1ms <= x <= 1000ms`\n\nThe execution time varies depending on the data supplied to the function, it may return very early or very late. The best case here is O(1) and the worst case is O(N).\n\n##### O(NlogN)\n\n```js\narr.sort(fn)\n```\n\n* 1000 elements ~= `10000ms`\n\nBrowsers usually implement the quicksort algorithm for the `sort()` method and the average time complexity of quicksort is O(NlgN). This is very efficient for large collections.\n\n##### O(N^2)\n\n```js\nfor (let i = 0; i < arr.length; i++) {\n for (let j = 0; j < arr.length; j++) {\n // ...\n }\n}\n```\n\n* 1000 elements = `1000000ms`\n\nThe execution time rises quadratically with the number of elements. Usually the result of nesting loops.\n\n##### O(N!)\n\n```js\nconst permutations = arr => {\n if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr\n return arr.reduce(\n (acc, item, i) =>\n acc.concat(\n permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [\n item,\n ...val\n ])\n ),\n []\n )\n}\n```\n\n* 1000 elements = `Infinity` (practically) ms\n\nThe execution time rises extremely fast with even just 1 addition to the array.",
"goodToHear": [
"Be wary of nesting loops as execution time increases exponentially."
],
"links": [
"[Big O Notation in JavaScript](https://medium.com/cesars-tech-insights/big-o-notation-javascript-25c79f50b19b)"
],
"tags": [
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\narr[arr.length - 1]\n```",
"```js\narr.filter(fn)\n```",
"```js\narr.some(fn)\n```",
"```js\narr.sort(fn)\n```",
"```js\nfor (let i = 0; i < arr.length; i++) {\n for (let j = 0; j < arr.length; j++) {\n // ...\n }\n}\n```",
"```js\nconst permutations = arr => {\n if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr\n return arr.reduce(\n (acc, item, i) =>\n acc.concat(\n permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [\n item,\n ...val\n ])\n ),\n []\n )\n}\n```"
]
},
{
"name": "bind-function.md",
"question": "Create a standalone function `bind` that is functionally equivalent to the method `Function.prototype.bind`.\n\n```js\nfunction example() {\n console.log(this)\n}\nconst boundExample = bind(example, { a: true })\nboundExample.call({ b: true }) // logs { a: true }\n```",
"answer": "Return a function that accepts an arbitrary number of arguments by gathering them with the rest `...` operator. From that function, return the result of calling the `fn` with `Function.prototype.apply` to apply the context and the array of arguments to the function.\n\n```js\nconst bind = (fn, context) => (...args) => fn.apply(context, args)\n```",
"goodToHear": [],
"links": [],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [
"```js\nfunction example() {\n console.log(this)\n}\nconst boundExample = bind(example, { a: true })\nboundExample.call({ b: true }) // logs { a: true }\n```"
],
"answerCodeBlocks": [
"```js\nconst bind = (fn, context) => (...args) => fn.apply(context, args)\n```"
]
},
{
"name": "cache-busting.md",
"question": "What is the purpose of cache busting and how can you achieve it?",
"answer": "Browsers have a cache to temporarily store files on websites so they don't need to be re-downloaded again when switching between pages or reloading the same page. The server is set up to send headers that tell the browser to store the file for a given amount of time. This greatly increases website speed and preserves bandwidth.\n\nHowever, it can cause problems when the website has been changed by developers because the user's cache still references old files. This can either leave them with old functionality or break a website if the cached CSS and JavaScript files are referencing elements that no longer exist, have moved or have been renamed.\n\nCache busting is the process of forcing the browser to download the new files. This is done by naming the file something different to the old file.\n\nA common technique to force the browser to re-download the file is to append a query string to the end of the file.\n\n* `src=\"js/script.js\"` => `src=\"js/script.js?v=2\"`\n\nThe browser considers it a different file but prevents the need to change the file name.",
"goodToHear": [],
"links": [
"[Strategies for cache-busting CSS](https://css-tricks.com/strategies-for-cache-busting-css/)"
],
"tags": [
"html"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "callback-hell.md",
"question": "How can you avoid callback hells?\n\n```js\ngetData(function(a) {\n getMoreData(a, function(b) {\n getMoreData(b, function(c) {\n getMoreData(c, function(d) {\n getMoreData(d, function(e) {\n // ...\n })\n })\n })\n })\n})\n```",
"answer": "Refactoring the functions to return promises and using `async/await` is usually the best option. Instead of supplying the functions with callbacks that cause deep nesting, they return a promise that can be `await`ed and will be resolved once the data has arrived, allowing the next line of code to be evaluated in a sync-like fashion.\n\nThe above code can be restructured like so:\n\n```js\nasync function asyncAwaitVersion() {\n const a = await getData()\n const b = await getMoreData(a)\n const c = await getMoreData(b)\n const d = await getMoreData(c)\n const e = await getMoreData(d)\n // ...\n}\n```\n\nThere are lots of ways to solve the issue of callback hells:\n\n* Modularization: break callbacks into independent functions\n* Use a control flow library, like async\n* Use generators with Promises\n* Use async/await (from v7 on)",
"goodToHear": [
"As an efficient JavaScript developer, you have to avoid the constantly growing indentation level, produce clean and readable code and be able to handle complex flows."
],
"links": [
"[Avoiding Callback Hell in Node.js](http://stackabuse.com/avoiding-callback-hell-in-node-js/)",
"[Asynchronous JavaScript: From Callback Hell to Async and Await](https://blog.hellojs.org/asynchronous-javascript-from-callback-hell-to-async-and-await-9b9ceb63c8e8)"
],
"tags": [
"node",
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [
"```js\ngetData(function(a) {\n getMoreData(a, function(b) {\n getMoreData(b, function(c) {\n getMoreData(c, function(d) {\n getMoreData(d, function(e) {\n // ...\n })\n })\n })\n })\n})\n```"
],
"answerCodeBlocks": [
"```js\nasync function asyncAwaitVersion() {\n const a = await getData()\n const b = await getMoreData(a)\n const c = await getMoreData(b)\n const d = await getMoreData(c)\n const e = await getMoreData(d)\n // ...\n}\n```"
]
},
{
"name": "callback-in-setState.md",
"question": "What is the purpose of callback function as an argument of `setState`?",
"answer": "The callback function is invoked when `setState` has finished and the component gets rendered. Since `setState` is asynchronous, the callback function is used for any post action.\n\n```js\nsetState({ name: \"sudheer\" }, () => {\n console.log(\"The name has updated and component re-rendered\")\n})\n```",
"goodToHear": [
"The callback function is invoked after `setState` finishes and is used for any post action.",
"It is recommended to use lifecycle method rather this callback function."
],
"links": [
"[React docs on `setState`](https://reactjs.org/docs/react-component.html#setstate)"
],
"tags": [
"react",
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nsetState({ name: \"sudheer\" }, () => {\n console.log(\"The name has updated and component re-rendered\")\n})\n```"
]
},
{
"name": "callback-refs-vs-finddomnode.md",
"question": "Which is the preferred option between callback refs and findDOMNode()?",
"answer": "Callback refs are preferred over the `findDOMNode()` API, due to the fact that `findDOMNode()` prevents certain improvements in React in the future.\n\n```js\n// Legacy approach using findDOMNode()\nclass MyComponent extends Component {\n componentDidMount() {\n findDOMNode(this).scrollIntoView()\n }\n\n render() {\n return <div />\n }\n}\n\n// Recommended approach using callback refs\nclass MyComponent extends Component {\n componentDidMount() {\n this.node.scrollIntoView()\n }\n\n render() {\n return <div ref={node => (this.node = node)} />\n }\n}\n```",
"goodToHear": [
"Callback refs are preferred over `findDOMNode()`."
],
"links": [
"[React docs on Refs and the DOM](https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components)"
],
"tags": [
"react",
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\n// Legacy approach using findDOMNode()\nclass MyComponent extends Component {\n componentDidMount() {\n findDOMNode(this).scrollIntoView()\n }\n\n render() {\n return <div />\n }\n}\n\n// Recommended approach using callback refs\nclass MyComponent extends Component {\n componentDidMount() {\n this.node.scrollIntoView()\n }\n\n render() {\n return <div ref={node => (this.node = node)} />\n }\n}\n```"
]
},
{
"name": "callbacks.md",
"question": "What is a callback? Can you show an example using one?",
"answer": "Callbacks are functions passed as an argument to another function to be executed once an event has occurred or a certain task is complete, often used in asynchronous code. Callback functions are invoked later by a piece of code but can be declared on initialization without being invoked.\n\nAs an example, event listeners are asynchronous callbacks that are only executed when a specific event occurs.\n\n```js\nfunction onClick() {\n console.log(\"The user clicked on the page.\")\n}\ndocument.addEventListener(\"click\", onClick)\n```\n\nHowever, callbacks can also be synchronous. The following `map` function takes a callback function that is invoked synchronously for each iteration of the loop (array element).\n\n```js\nconst map = (arr, callback) => {\n const result = []\n for (let i = 0; i < arr.length; i++) {\n result.push(callback(arr[i], i))\n }\n return result\n}\nmap([1, 2, 3, 4, 5], n => n * 2) // [2, 4, 6, 8, 10]\n```",
"goodToHear": [
"Functions are first-class objects in JavaScript",
"Callbacks vs Promises"
],
"links": [
"[MDN docs for callbacks](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nfunction onClick() {\n console.log(\"The user clicked on the page.\")\n}\ndocument.addEventListener(\"click\", onClick)\n```",
"```js\nconst map = (arr, callback) => {\n const result = []\n for (let i = 0; i < arr.length; i++) {\n result.push(callback(arr[i], i))\n }\n return result\n}\nmap([1, 2, 3, 4, 5], n => n * 2) // [2, 4, 6, 8, 10]\n```"
]
},
{
"name": "children-prop.md",
"question": "What is the `children` prop?",
"answer": "`children` is part of the props object passed to components that allows components to be passed as data to other components, providing the ability to compose components cleanly. There are a number of methods available in the React API to work with this prop, such as `React.Children.map`, `React.Children.forEach`, `React.Children.count`, `React.Children.only` and `React.Children.toArray`. A simple usage example of the children prop is as follows:\n\n```js\nfunction GenericBox({ children }) {\n return <div className=\"container\">{children}</div>\n}\n\nfunction App() {\n return (\n <GenericBox>\n <span>Hello</span> <span>World</span>\n </GenericBox>\n )\n}\n```",
"goodToHear": [
"Children is a prop that allows components to be passed as data to other components.",
"The React API provides methods to work with this prop."
],
"links": [
"[React docs on Children](https://reactjs.org/docs/jsx-in-depth.html#children-in-jsx)"
],
"tags": [
"react",
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nfunction GenericBox({ children }) {\n return <div className=\"container\">{children}</div>\n}\n\nfunction App() {\n return (\n <GenericBox>\n <span>Hello</span> <span>World</span>\n </GenericBox>\n )\n}\n```"
]
},
{
"name": "class-name.md",
"question": "Why does React use `className` instead of `class` like in HTML?",
"answer": "React's philosophy in the beginning was to align with the browser DOM API rather than HTML, since that more closely represents how elements are created. Setting a `class` on an element meant using the `className` API:\n\n```js\nconst element = document.createElement(\"div\")\nelement.className = \"hello\"\n```\n\nAdditionally, before ES5, reserved words could not be used in objects:\n\n```js\nconst element = {\n attributes: {\n class: \"hello\"\n }\n}\n```\n\nIn IE8, this will throw an error.\n\nIn modern environments, destructuring will throw an error if trying to assign to a variable:\n\n```js\nconst { class } = this.props // Error\nconst { className } = this.props // All good\nconst { class: className } = this.props // All good, but cumbersome!\n```\n\nHowever, `class` _can_ be used as a prop without problems, as seen in other libraries like Preact. React currently allows you to use `class`, but will throw a warning and convert it to `className` under the hood. There is currently an open thread (as of January 2019) discussing changing `className` to `class` to reduce confusion.",
"goodToHear": [],
"links": [],
"tags": [
"react"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst element = document.createElement(\"div\")\nelement.className = \"hello\"\n```",
"```js\nconst element = {\n attributes: {\n class: \"hello\"\n }\n}\n```",
"```js\nconst { class } = this.props // Error\nconst { className } = this.props // All good\nconst { class: className } = this.props // All good, but cumbersome!\n```"
]
},
{
"name": "clone-object.md",
"question": "How do you clone an object in JavaScript?",
"answer": "Using the object spread operator `...`, the object's own enumerable properties can be copied\ninto the new object. This creates a shallow clone of the object.\n\n```js\nconst obj = { a: 1, b: 2 }\nconst shallowClone = { ...obj }\n```\n\nWith this technique, prototypes are ignored. In addition, nested objects are not cloned, but rather their references get copied, so nested objects still refer to the same objects as the original. Deep-cloning is much more complex in order to effectively clone any type of object (Date, RegExp, Function, Set, etc) that may be nested within the object.\n\nOther alternatives include:\n\n* `JSON.parse(JSON.stringify(obj))` can be used to deep-clone a simple object, but it is CPU-intensive and only accepts valid JSON (therefore it strips functions and does not allow circular references).\n* `Object.assign({}, obj)` is another alternative.\n* `Object.keys(obj).reduce((acc, key) => (acc[key] = obj[key], acc), {})` is another more verbose alternative that shows the concept in greater depth.",
"goodToHear": [
"JavaScript passes objects by reference, meaning that nested objects get their references copied, instead of their values.",
"The same method can be used to merge two objects."
],
"links": [
"[MDN docs for Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)",
"[Clone an object in vanilla JS](http://voidcanvas.com/clone-an-object-in-vanilla-js-in-depth/)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst obj = { a: 1, b: 2 }\nconst shallowClone = { ...obj }\n```"
]
},
{
"name": "closures.md",
"question": "What is a closure? Can you give a useful example of one?",
"answer": "A closure is a function defined inside another function and has access to its lexical scope even when it is executing outside its lexical scope. The closure has access to variables in three scopes:\n\n* Variables declared in its own scope\n* Variables declared in the scope of the parent function\n* Variables declared in the global scope\n\nIn JavaScript, all functions are closures because they have access to the outer scope, but most functions don't utilise the usefulness of closures: the persistence of state. Closures are also sometimes called stateful functions because of this.\n\nIn addition, closures are the only way to store private data that can't be accessed from the outside in JavaScript. They are the key to the UMD (Universal Module Definition) pattern, which is frequently used in libraries that only expose a public API but keep the implementation details private, preventing name collisions with other libraries or the user's own code.",
"goodToHear": [
"Closures are useful because they let you associate data with a function that operates on that data.",
"A closure can substitute an object with only a single method.",
"Closures can be used to emulate private properties and methods."
],
"links": [
"[MDN docs for closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)",
"[What is a closure](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36)",
"[I never understood JavaScript closures](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)"
],
"tags": [
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "comparing-objects.md",
"question": "How do you compare two objects in JavaScript?",
"answer": "Even though two different objects can have the same properties with equal values, they are not considered equal when compared using `==` or `===`. This is because they are being compared by their reference (location in memory), unlike primitive values which are compared by value.\n\nIn order to test if two objects are equal in structure, a helper function is required. It will\niterate through the own properties of each object to test if they have the same values, including nested objects.\nOptionally, the prototypes of the objects may also be tested for equivalence by passing `true` as the 3rd argument.\n\nNote: this technique does not attempt to test equivalence of data structures other than\nplain objects, arrays, functions, dates and primitive values.\n\n```js\nfunction isDeepEqual(obj1, obj2, testPrototypes = false) {\n if (obj1 === obj2) {\n return true\n }\n\n if (typeof obj1 === \"function\" && typeof obj2 === \"function\") {\n return obj1.toString() === obj2.toString()\n }\n\n if (obj1 instanceof Date && obj2 instanceof Date) {\n return obj1.getTime() === obj2.getTime()\n }\n\n if (\n Object.prototype.toString.call(obj1) !==\n Object.prototype.toString.call(obj2) ||\n typeof obj1 !== \"object\"\n ) {\n return false\n }\n\n const prototypesAreEqual = testPrototypes\n ? isDeepEqual(\n Object.getPrototypeOf(obj1),\n Object.getPrototypeOf(obj2),\n true\n )\n : true\n\n const obj1Props = Object.getOwnPropertyNames(obj1)\n const obj2Props = Object.getOwnPropertyNames(obj2)\n\n return (\n obj1Props.length === obj2Props.length &&\n prototypesAreEqual &&\n obj1Props.every(prop => isDeepEqual(obj1[prop], obj2[prop]))\n )\n}\n```",
"goodToHear": [
"Primitives like strings and numbers are compared by their value",
"Objects on the other hand are compared by their reference (location in memory)"
],
"links": [
"[Object Equality in JavaScript](http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html)",
"[Deep comparison between two values](https://30secondsofcode.org/object#equals)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nfunction isDeepEqual(obj1, obj2, testPrototypes = false) {\n if (obj1 === obj2) {\n return true\n }\n\n if (typeof obj1 === \"function\" && typeof obj2 === \"function\") {\n return obj1.toString() === obj2.toString()\n }\n\n if (obj1 instanceof Date && obj2 instanceof Date) {\n return obj1.getTime() === obj2.getTime()\n }\n\n if (\n Object.prototype.toString.call(obj1) !==\n Object.prototype.toString.call(obj2) ||\n typeof obj1 !== \"object\"\n ) {\n return false\n }\n\n const prototypesAreEqual = testPrototypes\n ? isDeepEqual(\n Object.getPrototypeOf(obj1),\n Object.getPrototypeOf(obj2),\n true\n )\n : true\n\n const obj1Props = Object.getOwnPropertyNames(obj1)\n const obj2Props = Object.getOwnPropertyNames(obj2)\n\n return (\n obj1Props.length === obj2Props.length &&\n prototypesAreEqual &&\n obj1Props.every(prop => isDeepEqual(obj1[prop], obj2[prop]))\n )\n}\n```"
]
},
{
"name": "context.md",
"question": "What is context?",
"answer": "Context provides a way to pass data through the component tree without having to pass props down manually at every level. For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.\n\n```js\nconst { Provider, Consumer } = React.createContext(defaultValue)\n```",
"goodToHear": [
"Context provides a way to pass data through a tree of React components, without having to manually pass props.",
"Context is designed to share data that is considered _global_ for a tree of React components."
],
"links": [
"[React docs on Context](https://reactjs.org/docs/context.html)"
],
"tags": [
"react",
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst { Provider, Consumer } = React.createContext(defaultValue)\n```"
]
},
{
"name": "cors.md",
"question": "What is CORS?",
"answer": "Cross-Origin Resource Sharing or CORS is a mechanism that uses additional HTTP headers to grant a browser permission to access resources from a server at an origin different from the website origin.\n\nAn example of a cross-origin request is a web application served from `http://mydomain.com` that uses AJAX to make a request for `http://yourdomain.com`.\n\nFor security reasons, browsers restrict cross-origin HTTP requests initiated by JavaScript. `XMLHttpRequest` and `fetch` follow the same-origin policy, meaning a web application using those APIs can only request HTTP resources from the same origin the application was accessed, unless the response from the other origin includes the correct CORS headers.",
"goodToHear": [
"CORS behavior is not an error, it’s a security mechanism to protect users.",
"CORS is designed to prevent a malicious website that a user may unintentionally visit from making a request to a legitimate website to read their personal data or perform actions against their will."
],
"links": [
"[MDN docs for CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "css-box-model.md",
"question": "Describe the layout of the CSS Box Model and briefly describe each component.",
"answer": "<!-- Your answer goes here. -->\n\n`Content`: The inner-most part of the box filled with content, such as text, an image, or video player. It has the dimensions `content-box width` and `content-box height`.\n\n`Padding`: The transparent area surrounding the content. It has dimensions `padding-box width` and `padding-box height`.\n\n`Border`: The area surrounding the padding (if any) and content. It has dimensions `border-box width` and `border-box height`.\n\n_Margin_: The transparent outer-most layer that surrounds the border. It separates the element from other elements in the DOM. It has dimensions `margin-box width` and `margin-box height`.\n\n![alt text](https://www.washington.edu/accesscomputing/webd2/student/unit3/images/boxmodel.gif)",
"goodToHear": [
"This is a very common question asked during front-end interviews and while it may seem easy, it is critical you know it well!",
"Shows a solid understanding of spacing and the DOM"
],
"links": [
"[W3School's CSS Box Model Page](https://www.w3schools.com/Css/css_boxmodel.asp)",
"[Mozilla's Intro to the CSS Box Model](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model)"
],
"tags": [
"css"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "css-preprocessors.md",
"question": "What are the advantages of using CSS preprocessors?",
"answer": "CSS preprocessors add useful functionality that native CSS does not have, and generally make CSS neater and more maintainable by enabling DRY (Don't Repeat Yourself) principles. Their terse syntax for nested selectors cuts down on repeated code. They provide variables for consistent theming (however, CSS variables have largely replaced this functionality) and additional tools like color functions (`lighten`, `darken`, `transparentize`, etc), mixins, and loops that make CSS more like a real programming language and gives the developer more power to generate complex CSS.",
"goodToHear": [
"They allow us to write more maintainable and scalable CSS",
"Some disadvantages of using CSS preprocessors (setup, re-compilation time can be slow etc.)"
],
"links": [
"[CSS Preprocessors](https://medium.com/@garyfagan/css-preprocessors-6f226fa16f27)"
],
"tags": [
"css"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "css-sibling-selectors.md",
"question": "What is the difference between '+' and '~' sibling selectors?.",
"answer": "The General Sibling Selector `~` selects all elements that are siblings of a specified element.\n\nThe following example selects all `<p>` elements that are siblings of `<div>` elements:\n\n```css\ndiv ~ p {\n background-color: blue;\n}\n```\n\nThe Adjacent Sibling Selector `+` selects all elements that are the adjacent siblings of a specified element.\n\nThe following example will select all `<p>` elements that are placed immediately after `<div>` elements:\n\n```css\ndiv + p {\n background-color: red;\n}\n```",
"goodToHear": [],
"links": [
"[W3School's CSS Combinators Page](https://www.w3schools.com/css/css_combinators.asp)",
"[Mozilla's Combinators and groups of selectors page](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Combinators_and_multiple_selectors)"
],
"tags": [
"css"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```css\ndiv ~ p {\n background-color: blue;\n}\n```",
"```css\ndiv + p {\n background-color: red;\n}\n```"
]
},
{
"name": "css-specificity.md",
"question": "Can you describe how CSS specificity works?",
"answer": "Assuming the browser has already determined the set of rules for an element, each rule is assigned a matrix of values, which correspond to the following from highest to lowest specificity:\n\n* Inline rules (binary - 1 or 0)\n* Number of id selectors\n* Number of class, pseudo-class and attribute selectors\n* Number of tags and pseudo-element selectors\n\nWhen two selectors are compared, the comparison is made on a per-column basis (e.g. an id selector will always be higher than any amount of class selectors, as ids have higher specificity than classes). In cases of equal specificity between multiple rules, the rules that comes last in the page's style sheet is deemed more specific and therefore applied to the element.",
"goodToHear": [
"Specificity matrix: [inline, id, class/pseudo-class/attribute, tag/pseudo-element]",
"In cases of equal specificity, last rule is applied"
],
"links": [
"[CSS Specificity](https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/)"
],
"tags": [
"css"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "dom.md",
"question": "What is the DOM?",
"answer": "The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes. These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.",
"goodToHear": [
"The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API.",
"The DOM is constructed progressively in the browser as a page loads, which is why scripts are often placed at the bottom of a page, in the `<head>` with a `defer` attribute, or inside a `DOMContentLoaded` event listener. Scripts that manipulate DOM nodes should be run after the DOM has been constructed to avoid errors.",
"`document.getElementById()` and `document.querySelector()` are common functions for selecting DOM nodes.",
"Setting the `innerHTML` property to a new value runs the string through the HTML parser, offering an easy way to append dynamic HTML content to a node."
],
"links": [
"[MDN docs for DOM](https://developer.mozilla.org/en-US/docs/DOM)"
],
"tags": [
"html",
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "double-vs-triple-equals.md",
"question": "What is the difference between the equality operators `==` and `===`?",
"answer": "Triple equals (`===`) checks for strict equality, which means both the type and value must be the same. Double equals (`==`) on the other hand first performs type coercion so that both operands are of the same type and then applies strict comparison.",
"goodToHear": [
"Whenever possible, use triple equals to test equality because loose equality `==` can have unintuitive results.",
"Type coercion means the values are converted into the same type.",
"Mention of falsy values and their comparison."
],
"links": [
"[MDN docs for comparison operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)"
],
"tags": [
"javascript"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "element-vs-component.md",
"question": "What is the difference between an element and a component in React?",
"answer": "An element is a plain JavaScript object that represents a DOM node or component. Elements are pure and never mutated, and are cheap to create.\n\nA component is a function or class. Components can have state and take props as input and return an element tree as output (although they can represent generic containers or wrappers and don't necessarily have to emit DOM). Components can initiate side effects in lifecycle methods (e.g. AJAX requests, DOM mutations, interfacing with 3rd party libraries) and may be expensive to create.\n\n```js\nconst Component = () => \"Hello\"\nconst componentElement = <Component />\nconst domNodeElement = <div />\n```",
"goodToHear": [
"Elements are immutable, plain objects that describe the DOM nodes or components you want to render.",
"Components can be either classes or functions, that take props as an input and return an element tree as the output."
],
"links": [
"[React docs on Rendering Elements](https://reactjs.org/docs/rendering-elements.html)",
"[React docs on Components and Props](https://reactjs.org/docs/components-and-props.html)"
],
"tags": [
"react",
"javascript"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst Component = () => \"Hello\"\nconst componentElement = <Component />\nconst domNodeElement = <div />\n```"
]
},
{
"name": "em-rem-difference.md",
"question": "What is the difference between `em` and `rem` units?",
"answer": "Both `em` and `rem` units are based on the `font-size` CSS property. The only difference is where they inherit their values from.\n\n* `em` units inherit their value from the `font-size` of the parent element\n* `rem` units inherit their value from the `font-size` of the root element (`html`)\n\nIn most browsers, the `font-size` of the root element is set to `16px` by default.",
"goodToHear": [
"Benefits of using `em` and `rem` units"
],
"links": [
"[CSS units for font-size: px | em | rem](https://medium.com/code-better/css-units-for-font-size-px-em-rem-79f7e592bb97)"
],
"tags": [
"css"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "error-boundaries.md",
"question": "What are error boundaries in React?",
"answer": "Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.\n\nClass components become error boundaries if they define either (or both) of the lifecycle methods `static getDerivedStateFromError()` or `componentDidCatch().`\n\n```js\nclass ErrorBoundary extends React.Component {\n constructor(props) {\n super(props)\n this.state = { hasError: false }\n }\n\n // Use componentDidCatch to log the error\n componentDidCatch(error, info) {\n // You can also log the error to an error reporting service\n logErrorToMyService(error, info)\n }\n \n // use getDerivedStateFromError to update state\n static getDerivedStateFromError(error) {\n // Display fallback UI\n return { hasError: true };\n }\n\n\n render() {\n if (this.state.hasError) {\n // You can render any custom fallback UI\n return <h1>Something went wrong.</h1>\n }\n return this.props.children\n }\n}\n```",
"goodToHear": [
"Error boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself."
],
"links": [
"https://reactjs.org/docs/error-boundaries.html"
],
"tags": [
"react"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nclass ErrorBoundary extends React.Component {\n constructor(props) {\n super(props)\n this.state = { hasError: false }\n }\n\n // Use componentDidCatch to log the error\n componentDidCatch(error, info) {\n // You can also log the error to an error reporting service\n logErrorToMyService(error, info)\n }\n \n // use getDerivedStateFromError to update state\n static getDerivedStateFromError(error) {\n // Display fallback UI\n return { hasError: true };\n }\n\n\n render() {\n if (this.state.hasError) {\n // You can render any custom fallback UI\n return <h1>Something went wrong.</h1>\n }\n return this.props.children\n }\n}\n```"
]
},
{
"name": "event-delegation.md",
"question": "What is event delegation and why is it useful? Can you show an example of how to use it?",
"answer": "Event delegation is a technique of delegating events to a single common ancestor. Due to event bubbling, events \"bubble\" up the DOM tree by executing any handlers progressively on each ancestor element up to the root that may be listening to it.\n\nDOM events provide useful information about the element that initiated the event via `Event.target`. This allows the parent element to handle behavior as though the target element was listening to the event, rather than all children of the parent or the parent itself.\n\nThis provides two main benefits:\n\n* It increases performance and reduces memory consumption by only needing to register a single event listener to handle potentially thousands of elements.\n* If elements are dynamically added to the parent, there is no need to register new event listeners for them.\n\nInstead of:\n\n```js\ndocument.querySelectorAll(\"button\").forEach(button => {\n button.addEventListener(\"click\", handleButtonClick)\n})\n```\n\nEvent delegation involves using a condition to ensure the child target matches our desired element:\n\n```js\ndocument.addEventListener(\"click\", e => {\n if (e.target.closest(\"button\")) {\n handleButtonClick()\n }\n})\n```",
"goodToHear": [
"The difference between event bubbling and capturing"
],
"links": [
"[Event Delegation](https://davidwalsh.name/event-delegate)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\ndocument.querySelectorAll(\"button\").forEach(button => {\n button.addEventListener(\"click\", handleButtonClick)\n})\n```",
"```js\ndocument.addEventListener(\"click\", e => {\n if (e.target.closest(\"button\")) {\n handleButtonClick()\n }\n})\n```"
]
},
{
"name": "event-driven-programming.md",
"question": "What is event-driven programming?",
"answer": "Event-driven programming is a paradigm that involves building applications that send and receive events. When the program emits events, the program responds by running any callback functions that are registered to that event and context, passing in associated data to the function. With this pattern, events can be emitted into the wild without throwing errors even if no functions are subscribed to it.\n\nA common example of this is the pattern of elements listening to DOM events such as `click` and `mouseenter`, where a callback function is run when the event occurs.\n\n```js\ndocument.addEventListener(\"click\", function(event) {\n // This callback function is run when the user\n // clicks on the document.\n})\n```\n\nWithout the context of the DOM, the pattern may look like this:\n\n```js\nconst hub = createEventHub()\nhub.on(\"message\", function(data) {\n console.log(`${data.username} said ${data.text}`)\n})\nhub.emit(\"message\", {\n username: \"John\",\n text: \"Hello?\"\n})\n```\n\nWith this implementation, `on` is the way to _subscribe_ to an event, while `emit` is the way to _publish_ the event.",
"goodToHear": [
"Follows a publish-subscribe pattern.",
"Responds to events that occur by running any callback functions subscribed to the event.",
"Show how to create a simple pub-sub implementation with JavaScript."
],
"links": [
"[MDN docs on Events and Handlers](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Overview_of_Events_and_Handlers)",
"[Understanding Node.js event-driven architecture](https://medium.freecodecamp.org/understanding-node-js-event-driven-architecture-223292fcbc2d)"
],
"tags": [
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\ndocument.addEventListener(\"click\", function(event) {\n // This callback function is run when the user\n // clicks on the document.\n})\n```",
"```js\nconst hub = createEventHub()\nhub.on(\"message\", function(data) {\n console.log(`${data.username} said ${data.text}`)\n})\nhub.emit(\"message\", {\n username: \"John\",\n text: \"Hello?\"\n})\n```"
]
},
{
"name": "expression-vs-statement.md",
"question": "What is the difference between an expression and a statement in JavaScript?",
"answer": "There are two main syntactic categories in JavaScript: expressions and statements. A third one is both together, referred to as an expression statement. They are roughly summarized as:\n\n* **Expression**: produces a value\n* **Statement**: performs an action\n* **Expression statement**: produces a value and performs an action\n\nA general rule of thumb:\n\n> If you can print it or assign it to a variable, it’s an expression. If you can’t, it’s a statement.\n\n##### Statements\n\n```js\nlet x = 0\n\nfunction declaration() {}\n\nif (true) {\n}\n```\n\nStatements appear as instructions that do something but don't produce values.\n\n```js\n// Assign `x` to the absolute value of `y`.\nvar x\nif (y >= 0) {\n x = y\n} else {\n x = -y\n}\n```\n\nThe only expression in the above code is `y >= 0` which produces a value, either `true` or `false`. A value is not produced by other parts of the code.\n\n##### Expressions\n\nExpressions produce a value. They can be passed around to functions because the interpreter replaces them with the value they resolve to.\n\n```js\n5 + 5 // => 10\n\nlastCharacter(\"input\") // => \"t\"\n\ntrue === true // => true\n```\n\n##### Expression statements\n\nThere is an equivalent version of the set of statements used before as an expression using the conditional operator:\n\n```js\n// Assign `x` as the absolute value of `y`.\nvar x = y >= 0 ? y : -y\n```\n\nThis is both an expression and a statement, because we are declaring a variable `x` (statement) as an evaluation (expression).",
"goodToHear": [
"Function declarations vs function expressions"
],
"links": [
"[What is the difference between a statement and an expression?](https://stackoverflow.com/questions/12703214/javascript-difference-between-a-statement-and-an-expression)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nlet x = 0\n\nfunction declaration() {}\n\nif (true) {\n}\n```",
"```js\n// Assign `x` to the absolute value of `y`.\nvar x\nif (y >= 0) {\n x = y\n} else {\n x = -y\n}\n```",
"```js\n5 + 5 // => 10\n\nlastCharacter(\"input\") // => \"t\"\n\ntrue === true // => true\n```",
"```js\n// Assign `x` as the absolute value of `y`.\nvar x = y >= 0 ? y : -y\n```"
]
},
{
"name": "falsy-truthy.md",
"question": "What are truthy and falsy values in JavaScript?",
"answer": "A value is either truthy or falsy depending on how it is evaluated in a Boolean context. Falsy means false-like and truthy means true-like. Essentially, they are values that are coerced to `true` or `false` when performing certain operations.\n\nThere are 6 falsy values in JavaScript. They are:\n\n* `false`\n* `undefined`\n* `null`\n* `\"\"` (empty string)\n* `NaN`\n* `0` (both `+0` and `-0`)\n\nEvery other value is considered truthy.\n\nA value's truthiness can be examined by passing it into the `Boolean` function.\n\n```js\nBoolean(\"\") // false\nBoolean([]) // true\n```\n\nThere is a shortcut for this using the logical NOT `!` operator. Using `!` once will convert a value to its inverse boolean equivalent (i.e. not false is true), and `!` once more will convert back, thus effectively converting the value to a boolean.\n\n```js\n!!\"\" // false\n!![] // true\n```",
"goodToHear": [],
"links": [
"[Truthy on MDN](https://developer.mozilla.org/en/docs/Glossary/Truthy)",
"[Falsy on MDN](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nBoolean(\"\") // false\nBoolean([]) // true\n```",
"```js\n!!\"\" // false\n!![] // true\n```"
]
},
{
"name": "fibonacci.md",
"question": "Generate an array, containing the Fibonacci sequence, up until the nth term.",
"answer": "Initialize an empty array of length `n`. Use `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\n\n```js\nconst fibonacci = n =>\n [...Array(n)].reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n )\n```",
"goodToHear": [],
"links": [
"[Similar problem](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/snippets_archive/fibonacciUntilNum.md)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst fibonacci = n =>\n [...Array(n)].reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n )\n```"
]
},
{
"name": "flex-layout.md",
"question": "Using flexbox, create a 3-column layout where each column takes up a `col-{n} / 12` ratio of the container.\n\n```html\n<div class=\"row\">\n <div class=\"col-2\"></div>\n <div class=\"col-7\"></div>\n <div class=\"col-3\"></div>\n</div>\n```",
"answer": "Set the `.row` parent to `display: flex;` and use the `flex` shorthand property to give the column classes a `flex-grow` value that corresponds to its ratio value.\n\n```css\n.row {\n display: flex;\n}\n\n.col-2 {\n flex: 2;\n}\n\n.col-7 {\n flex: 7;\n}\n\n.col-3 {\n flex: 3;\n}\n```",
"goodToHear": [],
"links": [
"[MDN docs for basic concepts of flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox)",
"[A complete guide to Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)"
],
"tags": [
"css"
],
"expertise": 0,
"questionCodeBlocks": [
"```html\n<div class=\"row\">\n <div class=\"col-2\"></div>\n <div class=\"col-7\"></div>\n <div class=\"col-3\"></div>\n</div>\n```"
],
"answerCodeBlocks": [
"```css\n.row {\n display: flex;\n}\n\n.col-2 {\n flex: 2;\n}\n\n.col-7 {\n flex: 7;\n}\n\n.col-3 {\n flex: 3;\n}\n```"
]
},
{
"name": "floating-point.md",
"question": "What does `0.1 + 0.2 === 0.3` evaluate to?",
"answer": "It evaluates to `false` because JavaScript uses the IEEE 754 standard for Math and it makes use of 64-bit floating numbers. This causes precision errors when doing decimal calculations, in short, due to computers working in Base 2 while decimal is Base 10.\n\n```js\n0.1 + 0.2 // 0.30000000000000004\n```\n\nA solution to this problem would be to use a function that determines if two numbers are approximately equal by defining an error margin (epsilon) value that the difference between two values should be less than.\n\n```js\nconst approxEqual = (n1, n2, epsilon = 0.0001) => Math.abs(n1 - n2) < epsilon\napproxEqual(0.1 + 0.2, 0.3) // true\n```",
"goodToHear": [
"A simple solution to this problem"
],
"links": [
"[A simple helper function to check equality](https://github.com/Chalarangelo/30-seconds-of-code#approximatelyequal)",
"[Fix \"0.1 + 0.2 = 0.300000004\" in JavaScript](http://blog.blakesimpson.co.uk/read/61-fix-0-1-0-2-0-300000004-in-javascript)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\n0.1 + 0.2 // 0.30000000000000004\n```",
"```js\nconst approxEqual = (n1, n2, epsilon = 0.0001) => Math.abs(n1 - n2) < epsilon\napproxEqual(0.1 + 0.2, 0.3) // true\n```"
]
},
{
"name": "focus-ring.md",
"question": "What is a focus ring? What is the correct solution to handle them?",
"answer": "A focus ring is a visible outline given to focusable elements such as buttons and anchor tags. It varies depending on the vendor, but generally it appears as a blue outline around the element to indicate it is currently focused.\n\nIn the past, many people specified `outline: 0;` on the element to remove the focus ring. However, this causes accessibility issues for keyboard users because the focus state may not be clear. When not specified though, it causes an unappealing blue ring to appear around an element.\n\nIn recent times, frameworks like Bootstrap have opted to use a more appealing `box-shadow` outline to replace the default focus ring. However, this is still not ideal for mouse users.\n\nThe best solution is an upcoming pseudo-selector `:focus-visible` which can be polyfilled today with JavaScript. It will only show a focus ring if the user is using a keyboard and leave it hidden for mouse users. This keeps both aesthetics for mouse use and accessibility for keyboard use.",
"goodToHear": [],
"links": [
"[:focus-visible](https://css-tricks.com/focus-visible-and-backwards-compatibility/)"
],
"tags": [
"css"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "for-each-map.md",
"question": "What is the difference between the array methods `map()` and `forEach()`?",
"answer": "Both methods iterate through the elements of an array. `map()` maps each element to a new element by invoking the callback function on each element and returning a new array. On the other hand, `forEach()` invokes the callback function for each element but does not return a new array. `forEach()` is generally used when causing a side effect on each iteration, whereas `map()` is a common functional programming technique.",
"goodToHear": [
"Use `forEach()` if you need to iterate over an array and cause mutations to the elements without needing to return values to generate a new array.",
"`map()` is the right choice to keep data immutable where each value of the original array is mapped to a new array."
],
"links": [
"[MDN docs for forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)",
"[MDN docs for map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)",
"[JavaScript — Map vs. ForEach](https://codeburst.io/javascript-map-vs-foreach-f38111822c0f)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "fragments.md",
"question": "What are fragments?",
"answer": "Fragments allow a React component to return multiple elements without a wrapper, by grouping the children without adding extra elements to the DOM. Fragments offer better performance, lower memory usage, a cleaner DOM and can help in dealing with certain CSS mechanisms (e.g. tables, Flexbox and Grid).\n\n```js\nrender() {\n return (\n <React.Fragment>\n <ChildA />\n <ChildB />\n <ChildC />\n </React.Fragment>\n );\n}\n\n// Short syntax supported by Babel 7\nrender() {\n return (\n <>\n <ChildA />\n <ChildB />\n <ChildC />\n </>\n );\n}\n```",
"goodToHear": [
"Fragments group multiple elements returned from a component, without adding a DOM element around them."
],
"links": [
"[React docs on Fragments](https://reactjs.org/docs/fragments.html)"
],
"tags": [
"react",
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nrender() {\n return (\n <React.Fragment>\n <ChildA />\n <ChildB />\n <ChildC />\n </React.Fragment>\n );\n}\n\n// Short syntax supported by Babel 7\nrender() {\n return (\n <>\n <ChildA />\n <ChildB />\n <ChildC />\n </>\n );\n}\n```"
]
},
{
"name": "functional-programming.md",
"question": "What is functional programming?",
"answer": "Functional programming is a paradigm in which programs are built in a declarative manner using pure functions that avoid shared state and mutable data. Functions that always return the same value for the same input and don't produce side effects are the pillar of functional programming. Many programmers consider this to be the best approach to software development as it reduces bugs and cognitive load.",
"goodToHear": [
"Cleaner, more concise development experience",
"Simple function composition",
"Features of JavaScript that enable functional programming (`.map`, `.reduce` etc.)",
"JavaScript is multi-paradigm programming language (Object-Oriented Programming and Functional Programming live in harmony)"
],
"links": [
"[Javascript and Functional Programming: An Introduction](https://hackernoon.com/javascript-and-functional-programming-an-introduction-286aa625e26d)",
"[Master the JavaScript Interview: What is Functional Programming?](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0)"
],
"tags": [
"javascript"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "hoc-component.md",
"question": "What are higher-order components?",
"answer": "A higher-order component (HOC) is a function that takes a component as an argument and returns a new component. It is a pattern that is derived from React’s compositional nature. Higher-order components are like **pure components** because they accept any dynamically provided child component, but they won’t modify or copy any behavior from their input components.\n\n```js\nconst EnhancedComponent = higherOrderComponent(WrappedComponent)\n```",
"goodToHear": [
"They can be used for state abstraction and manipulation, props manipulation, render high jacking, etc."
],
"links": [],
"tags": [
"react"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst EnhancedComponent = higherOrderComponent(WrappedComponent)\n```"
]
},
{
"name": "hoisting-example.md",
"question": "What will the console log in this example?\n\n```js\nvar foo = 1\nvar foobar = function() {\n console.log(foo)\n var foo = 2\n}\nfoobar()\n```",
"answer": "Due to hoisting, the local variable `foo` is declared before the `console.log` method is called. This means the local variable `foo` is passed as an argument to `console.log()` instead of the global one declared outside of the function. However, since the value is not hoisted with the variable declaration, the output will be `undefined`, not `2`.",
"goodToHear": [
"Hoisting is JavaScript’s default behavior of moving declarations to the top",
"Mention of `strict` mode"
],
"links": [
"[MDN docs for hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [
"```js\nvar foo = 1\nvar foobar = function() {\n console.log(foo)\n var foo = 2\n}\nfoobar()\n```"
],
"answerCodeBlocks": []
},
{
"name": "hoisting.md",
"question": "How does hoisting work in JavaScript?",
"answer": "Hoisting is a JavaScript mechanism where variable and function declarations are put into memory during the compile phase. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.\n\nHowever, the value is not hoisted with the declaration.\n\nThe following snippet:\n\n```js\nconsole.log(hoist)\nvar hoist = \"value\"\n```\n\nis equivalent to:\n\n```js\nvar hoist\nconsole.log(hoist)\nhoist = \"value\"\n```\n\nTherefore logging `hoist` outputs `undefined` to the console, not `\"value\"`.\n\nHoisting also allows you to invoke a function declaration before it appears to be declared in a program.\n\n```js\nmyFunction() // No error; logs \"hello\"\nfunction myFunction() {\n console.log(\"hello\")\n}\n```\n\nBut be wary of function expressions that are assigned to a variable:\n\n```js\nmyFunction() // Error: `myFunction` is not a function\nvar myFunction = function() {\n console.log(\"hello\")\n}\n```",
"goodToHear": [
"Hoisting is JavaScript’s default behavior of moving declarations to the top",
"Functions declarations are hoisted before variable declarations"
],
"links": [
"[MDN docs for hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)",
"[Understanding Hoisting in JavaScript](https://scotch.io/tutorials/understanding-hoisting-in-javascript)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconsole.log(hoist)\nvar hoist = \"value\"\n```",
"```js\nvar hoist\nconsole.log(hoist)\nhoist = \"value\"\n```",
"```js\nmyFunction() // No error; logs \"hello\"\nfunction myFunction() {\n console.log(\"hello\")\n}\n```",
"```js\nmyFunction() // Error: `myFunction` is not a function\nvar myFunction = function() {\n console.log(\"hello\")\n}\n```"
]
},
{
"name": "html-multiple-header-footers.md",
"question": "Can a web page contain multiple `<header>` elements? What about `<footer>` elements?",
"answer": "Yes to both. The W3 documents state that the tags represent the header(`<header>`) and footer(`<footer>`) areas of their nearest ancestor \"section\". So not only can the page `<body>` contain a header and a footer, but so can every `<article>` and `<section>` element.",
"goodToHear": [
"W3 recommends having as many as you want, but only 1 of each for each \"section\" of your page, i.e. body, section etc."
],
"links": [
"[StackOverflow Using header or footer tag twice](https://stackoverflow.com/questions/4837269/html5-using-header-or-footer-tag-twice?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)"
],
"tags": [
"html"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "html-specification-implementation.md",
"question": "Discuss the differences between an HTML specification and a browser’s implementation thereof.",
"answer": "HTML specifications such as `HTML5` define a set of rules that a document must adhere to in order to be “valid” according to that specification. In addition, a specification provides instructions on how a browser must interpret and render such a document.\n\nA browser is said to “support” a specification if it handles valid documents according to the rules of the specification. As of yet, no browser supports all aspects of the `HTML5` specification (although all of the major browser support most of it), and as a result, it is necessary for the developer to confirm whether the aspect they are making use of will be supported by all of the browsers on which they hope to display their content. This is why cross-browser support continues to be a headache for developers, despite the improved specificiations.",
"goodToHear": [
"`HTML5` defines some rules to follow for an invalid `HTML5` document (i.e., one that contains syntactical errors)",
"However, invalid documents may contain anything, so it's impossible for the specification to handle all possibilities comprehensively.",
"Thus, many decisions about how to handle malformed documents are left up to the browser."
],
"links": [
"[HTML 5.2 WWW Specifications](https://www.w3.org/TR/html52/)"
],
"tags": [
"html"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "html-vs-react-event-handling.md",
"question": "What is the difference between HTML and React event handling?",
"answer": "In HTML, the attribute name is in all lowercase and is given a string invoking a function defined somewhere:\n\n```html\n<button onclick=\"handleClick()\"></button>\n```\n\nIn React, the attribute name is camelCase and are passed the function reference inside curly braces:\n\n```js\n<button onClick={handleClick} />\n```\n\nIn HTML, `false` can be returned to prevent default behavior, whereas in React `preventDefault` has to be called explicitly.\n\n```html\n<a href=\"#\" onclick=\"console.log('The link was clicked.'); return false\" />\n```\n\n```js\nfunction handleClick(e) {\n e.preventDefault()\n console.log(\"The link was clicked.\")\n}\n```",
"goodToHear": [
"HTML uses lowercase, React uses camelCase."
],
"links": [
"[React docs on Handling Events](https://reactjs.org/docs/handling-events.html)"
],
"tags": [
"react",
"javascript",
"html"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```html\n<button onclick=\"handleClick()\"></button>\n```",
"```js\n<button onClick={handleClick} />\n```",
"```html\n<a href=\"#\" onclick=\"console.log('The link was clicked.'); return false\" />\n```",
"```js\nfunction handleClick(e) {\n e.preventDefault()\n console.log(\"The link was clicked.\")\n}\n```"
]
},
{
"name": "html-vs-xhtml.md",
"question": "What are some differences that XHTML has compared to HTML?",
"answer": "Some of the key differences are:\n\n* An XHTML element must have an XHTML `<DOCTYPE>`\n* Attributes values must be enclosed in quotes\n* Attribute minimization is forbidden (e.g. one has to use `checked=\"checked\"` instead of `checked`)\n* Elements must always be properly nested\n* Elements must always be closed\n* Special characters must be escaped",
"goodToHear": [
"Any element can be self-closed",
"Tags ands attributes are case-sensitive, usually lowercase"
],
"links": [
"[W3Schools docs for HTML and XHTML](https://www.w3schools.com/html/html_xhtml.asp)"
],
"tags": [
"html"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "html5-semantic-elements-usage.md",
"question": "Briefly describe the correct usage of the following HTML5 semantic elements: `<header>`, `<article>`,`<section>`, `<footer>`",
"answer": "* `<header>` is used to contain introductory and navigational information about a section of the page. This can include the section heading, the author’s name, time and date of publication, table of contents, or other navigational information.\n\n* `<article>` is meant to house a self-contained composition that can logically be independently recreated outside of the page without losing its meaning. Individual blog posts or news stories are good examples.\n\n* `<section>` is a flexible container for holding content that shares a common informational theme or purpose.\n\n* `<footer>` is used to hold information that should appear at the end of a section of content and contain additional information about the section. Author’s name, copyright information, and related links are typical examples of such content.",
"goodToHear": [
"Other semantic elements are `<form>` and `<table>`"
],
"links": [
"[HTML 5 Semantic Elements](https://www.w3schools.com/html/html5_semantic_elements.asp)"
],
"tags": [
"html"
],
"expertise": 0,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "html5-web-storage.md",
"question": "What is HTML5 Web Storage? Explain `localStorage` and `sessionStorage`.",
"answer": "With HTML5, web pages can store data locally within the user’s browser.\nThe data is stored in name/value pairs, and a web page can only access data stored by itself.\n\n**Differences between `localStorage` and `sessionStorage` regarding lifetime:**\n\n* Data stored through `localStorage` is permanent: it does not expire and remains stored on the user’s computer until a web app deletes it or the user asks the browser to delete it.\n* `sessionStorage` has the same lifetime as the top-level window or browser tab in which the data got stored. When the tab is permanently closed, any data stored through `sessionStorage` is deleted.\n\n**Differences between `localStorage` and `sessionStorage` regarding storage scope:**\nBoth forms of storage are scoped to the document origin so that documents with different origins will never share the stored objects.\n\n* `sessionStorage` is also scoped on a per-window basis. Two browser tabs with documents from the same origin have separate `sessionStorage` data.\n* Unlike in `localStorage`, the same scripts from the same origin can't access each other's `sessionStorage` when opened in different tabs.",
"goodToHear": [
"Earlier, this was done with cookies.",
"The storage limit is far larger (at least 5MB) than with cookies and its faster.",
"The data is never transferred to the server and can only be used if the client specifically asks for it."
],
"links": [
"[W3Schools HTML5 Webstorage](https://www.w3schools.com/html/html5_webstorage.asp)"
],
"tags": [
"html"
],
"expertise": 2,
"questionCodeBlocks": [],
"answerCodeBlocks": []
},
{
"name": "iife.md",
"question": "What is the reason for wrapping the entire contents of a JavaScript source file in a function that is immediately invoked?",
"answer": "This technique is very common in JavaScript libraries. It creates a closure around the entire contents of the file which creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries. The function is immediately invoked so that the namespace (library name) is assigned the return value of the function.\n\n```js\nconst myLibrary = (function() {\n var privateVariable = 2\n return {\n publicMethod: () => privateVariable\n }\n})()\nprivateVariable // ReferenceError\nmyLibrary.publicMethod() // 2\n```",
"goodToHear": [
"Used among many popular JavaScript libraries",
"Creates a private namespace"
],
"links": [
"[MDN docs for closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)"
],
"tags": [
"javascript"
],
"expertise": 1,
"questionCodeBlocks": [],
"answerCodeBlocks": [
"```js\nconst myLibrary = (function() {\n var privateVariable = 2\n return {\n publicMethod: () => privateVariable\n }\n})()\nprivateVariable // ReferenceError\nmyLibrary.publicMethod() // 2\n```"
]
},
{
"name": "imperative-vs-declarative.md",
"question": "Explain the differences between imperative and declarative programming.",
"answer": "These two types of programming can roughly be summarized as:\n\n* Imperative: **how** to achieve something\n* Declarative: **what** should be achieved\n\nA common example of declarative programming is CSS. The developer specifies CSS properties that describe what something should look like rather than how to achieve it. The \"how\" is abstracted away by the browser.\n\nOn the other hand, imperative programming involves the steps required to achieve something. In JavaScript, the differences can be contrasted like so:\n\n##### Imperative\n\n```js\nconst numbers = [1, 2, 3, 4, 5]\nconst numbersDoubled = []\nfor (let i = 0; i < numbers.length; i++) {\n numbersDoubled[i] = numbers[i] * 2\n}\n```\n\nWe manually loop over the numbers of the array and assign the new index as the number doubled.\n\n##### Declarative\n\n```js\nconst numbers = [1, 2, 3, 4, 5]\nconst numbersDoubled = numbers.map(n => n * 2)\n```\n\nWe declare that the new array is mapped to a new one where each value is doubled.",
"goodToHear": [
"Declarative programming often works with functions and expressions. Imperative programming frequently uses statements and relies on low-level features that cause mutations, while declarative programming has a strong focus on abstraction and purity.",
"Declarative programming is more terse and easier to process at a glance."
],
"links": [
"[Declarative vs Imperative Programming](https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2)"