@@ -542,3 +542,92 @@ console.log(...question.values());
542
542
` ` `
543
543
544
544
# Summary: Which Data Structure to Use
545
+
546
+ Initially we had two main data structures, Arrays and Objects but we have looked at other data structures introduced to JavaScript from ES6.
547
+
548
+ It's important to know the pros and cons of all the data structures and which one to use at any given point.
549
+
550
+ ## Sources of Data
551
+
552
+ There are three main sources of Data,
553
+
554
+ - The Program: Data written directly in source code (E.g: Status Message)
555
+ - From the UI: Data input from the user or Data written in DOM (E.g tasks in a todo app).
556
+ - From External Sources: Data fetched for example from Web API (E.g recipe, objects)
557
+
558
+ ## Data Structures to Use
559
+
560
+ - Simple List: Arrays or Sets
561
+ - Key/Value Pairs: Objects or Maps
562
+
563
+ The most common source of Data is the Web API which commonly comes in a ` JSON ` format and for storing such data, arrays is usually the way to go.
564
+
565
+ Now there are other data structures not built into JavaScript like:
566
+
567
+ ### Other Built-In
568
+
569
+ - WeakMap
570
+ - WeakSet
571
+
572
+ ### Non-Built In
573
+
574
+ - Stacks
575
+ - Queues
576
+ - Linked Lists
577
+ - Trees
578
+ - Hash Tables
579
+
580
+ ## Arrays vs Sets & Objects vs Maps
581
+
582
+ ## Arrays
583
+
584
+ ` ` ` js
585
+ const tasks = [" Code" , " Eat" , " Code" ];
586
+ // ["Code", "Eat", "Code"]
587
+ ` ` `
588
+
589
+ 1. Use arrays when you need **ordered** list of values(with duplicates).
590
+ 2. Use arrays when you need to **manipulate** data
591
+
592
+ ## Sets
593
+
594
+ ` ` ` js
595
+ const task = new Set ([" Code" , " Eat" , " Code" ]);
596
+ // ["Code", "Eat"]
597
+ ` ` `
598
+
599
+ 1. Use Sets when you need to work with **unique** values.
600
+ 2. Use Sets when **high performance** is really important.
601
+ 3. Use Sets to **remove duplicates** from arrays.
602
+
603
+ ## Objects
604
+
605
+ ` ` ` js
606
+ const task = {
607
+ task: " code" ,
608
+ date: " today" ,
609
+ repeat: true ,
610
+ };
611
+ ` ` `
612
+
613
+ 1. More traditional key/value store
614
+ 2. Eaiser to write and access values with ` .` and ` []` notations
615
+ 3. Use when you need to include ` functions` (methods)
616
+ 4. Use when working with ` JSON ` (can covert to ` Map ` )
617
+
618
+ ## Maps
619
+
620
+ ` ` ` js
621
+ const task = new Map ([
622
+ [" task" , " code" ],
623
+ [" date" , " today" ],
624
+ [false , " start coding!" ],
625
+ ]);
626
+ ` ` `
627
+
628
+ 1. Better performance
629
+ 2. Keys can have any data type
630
+ 3. Easy to iterate
631
+ 4. Easy to compute size
632
+ 5. Use when you simply need to map key to values
633
+ 6. Use when you need keys that are not strings.
0 commit comments