const - JS | lectureData Structures, Modern Operators & Strings

Which Data Structure to Use?

Data Structures, Modern Operators & Strings

Dealing and working with data is the main thing we do as developers. That's why, since the beginning of the course, we have been working with JavaScript built-in data structures, like arrays and objects. Then in the last few lectures, we learned about two new data structures: sets and maps. We now have four data structures from which we can choose.

I decided to create this lecture to show you the pros and cons of each data structure and when to choose each. Let's start by quickly categorizing where data can come from. There are essentially three sources of data.

First, data can be written within the program source code itself, like status messages that a webpage will display based on user actions.

Second, data can come from the user interface. That is, from the webpage. It can either be data that the user inputs into some form or data that's already written somehow in the DOM. For example, this can be the user's tasks in a todo app or expenses in a budget app.

Finally, data can come from external sources, usually a web API. We haven't yet talked about web APIs. But to give you a general idea, API stands for Application Programming Interface, and we can use a web API to get data from other web applications. For example, we can use a web API to get the current weather in any city, data about movies or currency conversion rates, and every kind of data you can imagine. We will learn how all that works later in the course.

So no matter where the data comes from and what kind of data it is, we usually always have collections of data that we then need to store somewhere. And as you might have guessed, we use data structures.

But as you know, there are four built-in data structures in JavaScript. Hence, we now need a way of deciding between them, but it's not that hard. So the first question we need to ask ourselves is: Do we need a simple list of values? If so, then we're going to use an array or a set. But on the other hand, if we need key-value pairs, we need an object or a map. So the big difference here is that with a key-value pair, we have a way of describing the values using the key.

On the other hand, in a list like an array or a set, we simply have the values without any description. As a quick example, let's go back to getting data from a web API because that's usually the most common source of data in modern JavaScript applications. So data from web APIs usually comes in a special data format called JSON, which looks like the below code snippet.

{
  "count": 3,
  "users": [
    {
      "name": "John Doe",
      "age": 30,
      "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY",
        "zip": "12345"
      },
      "phone": ["123-456-7890", "234-567-8901"],
      "email": "john_doe@gmail.com",
      "hobbies": ["running", "reading", "coding"],
      "isMarried": false
    },
    {
      "name": "Jane Doe",
      "age": 25,
      "address": {
        "street": "456 Main St",
        "city": "New York",
        "state": "NY",
        "zip": "12345"
      },
      "phone": ["123-456-7890", "234-567-8901"],
      "email": "jane_doe@gmail.com",
      "hobbies": ["surfing", "walking", "bike riding"]
    },
    {
      "name": "Bob Doe",
      "age": 35,
      "address": {
        "street": "789 Main St",
        "city": "New York",
        "state": "NY",
        "zip": "12345"
      },
      "phone": ["123-456-7890", "234-567-8901"],
      "email": "bob_doe@gmail.xom",
      "hobbies": ["football", "basketball", "tennis"]
    }
  ]
}

JSON is essentially just text, i.e., a long string, but it can easily be converted to JavaScript objects because it uses the same formatting as JavaScript objects and arrays. In the JSON code snippet above, we have three objects that describe users. We have the values in green, like the name and age. And it makes complete sense that these values are then described using a key. Otherwise, we would have no idea what the different values are.

So key-value pairs are essential here, and that's why this data is stored in an object, not an array. Now, each of these user objects can be seen as a value. And since we have many of them, we have a collection of data again, and therefore we need a data structure to store them.

Now, do we want to describe each of the objects? Well, it's not necessary. We already know they are all users, and whatever information we need about the users is already stored right in each of the objects.

So all we want is a simple list where all the users are held together. And so here, an array is the perfect data structure for that. And in fact, creating an array of objects is extremely common in JavaScript. You will be working with this kind of data all the time as a professional JavaScript developer. And that's why I'm placing so much focus on this here.

Now, before we move on to compare arrays, sets, objects, and maps, I quickly want to mention that there are also Weaksets and WeakMaps data structures in JavaScript. Also, there are even more data structures that are used in programming but which are not built into JavaScript. Just to mention a few, these can be stacks, queues, linked lists, trees, or hash tables. It doesn't matter for now, but I still just wanted to let you know that there are more than just the four built-in data structures we learned.

Let's now talk a bit more about the built-in data structures. You already know how to use all of them, but it's essential to know when to use them. Starting with arrays versus sets, we already know that we should use them for simple lists of values when we do not need to describe them.

You should use arrays whenever you need to store values in order and when these values might contain duplicates. Also, you should always use arrays when you need to manipulate data because there are many helpful array methods.

Now sets, on the other hand, should only be used when you are working with unique values, besides that, you can also use sets in situations when high performance is essential because operations like searching for an item or deleting an item from a set can be up to 10 times faster in sets than in arrays.

Now one great use case for sets is to remove duplicate values from an array like we already did before. So sets are not meant to replace arrays but rather to complement them whenever we are dealing with unique values.

Now let's talk about objects versus maps. We already know that we should use these key-value data structures whenever we need to describe the values using keys. But when do we use objects? And when do we use maps?

Objects have been the traditional key-value data structure simply because we didn't have maps before ES6, but using objects as key-value stores has several technical disadvantages. And that's why some people say that we've been abusing objects for this.

On the other hand, Maps are way better suited for simple key-value stores because they offer better performance. Also, map keys can have any data type, and they're also easy to iterate, and it's easy to compute the size of a map.

However, the biggest advantage of objects is probably how easy it is to write them and access data by simply using the dot or the brackets operator. Also, most developers are already super used to objects. And so they keep using them for simple key-value stores.

To conclude, you should use maps when you need to map keys to values and when you need keys that are not strings because, as we saw in the last lecture, that can be very powerful sometimes. If you need functions as values, you should use an object for that. So in objects, these functions are then called methods, and you can use the this keyword to access properties of the same object, which is impossible in maps.

Also, when working with JSON data, as we saw above, you will probably be using objects for that unless you want to convert the objects to maps, but that's usually not something that we do. So, we still use objects all the time, but maps are also a very important data structure right now and way more important than sets.

Hopefully, you now have a good understanding of the different data structures and how to use them in JavaScript. Let's move on to the next lecture!