Built-in data structures in javascript
This article is going to be simple walkthrough of the typical built-in data structures in javascript, their usage, and differences.
Let's make it simple with more code and less text.
Data structures?
Different ways of storing, retrieving, and manipulating data. Simply managing data.
Built-in data structures in javascript
Any language will have it's set of built-in data structures to help us. Javascript built-in data structures are quite different in nature. They can be jotted as,
- Arrays
- Sets
- Objects and
- Maps
When and where to use?
Array
Just like any language, arrays in javascript help us to deal with a list of entities. Let's focus on how it varies in javascript.
- Dynamic - the size of the array dynamic (increase & decrease based on inputs)
- Mixed types - we can have mixed types in an array
Disadvantage
Finding elements and removing can be a bit costly. Since it involves iterating and shifting entities until it finds the match. If the size of the array is too large, this can definitely affect the performance of the application.
Imagine an array of size 1000, if you are splicing there will be unnecessary shiting of entities. This can be a huge performance issue.
In most cases, we will be using the array data structure for dealing list of entities.
Set
In such a case set data structure can be used.
- When you are not concerned about the order and in need to deal with unique values
Here you can easily check if a particular element is present or not using has() and access entities directly.
Object
- Objects - key-value pairs
- They are more than just a data structure, they can have methods associated and can do things extra
Map
- Key-value pairs, but they can be just used for storing
- Separate methods like get, set, delete, etc
Note: In both maps and objects, any duplicate entry would result in updation.
Weak map and weak set
- It's just a variation of the map and set
- values and keys are weakly referenced
- garbage collection would delete keys and values if not used anywhere else in the app
This can be a huge performance boost. We use it rarely, yet good to know.