Syntax Video
You Should Use Maps and Sets in JS
- 0:00 Intro
- 1:09 The problem with Objects
- 2:41 When to use a Map
- 3:07 How to use Map
- 4:34 Create a Map from an Object
- 4:59 Object Keys are Strings
- 5:59 Create a Map from an Array
- 7:02 Map methods are nice
- 7:45 JSON.stringify a Map
- 8:53 Sets
- 9:15 The problem with Array.includes
- 10:36 Making a Set with an Object
- 11:50 Create a Set from an Array
- 12:23 Sets and Duplicate Values
- 12:58 Set methods on MDN
- 13:21 Thanks for watching
Intro
JavaScript objects are a beautiful thing and they are actually one of the reasons I fell in love with the JavaScript language and you can do a lot of things with them whereas in other programming languages there are specific data structures for doing doing certain types of things so things like hashmaps or dictionaries anything that's like an associative array and the JavaScript object lets us Implement and do all of those things with just the object but there are certain scenarios where a JavaScript object maybe isn't the best choice and in this video we're going to talk about that now I'm not here to tell you to stop using objects and I'm not here to tell you that maps and sets are the only thing you should be using when working in JavaScript but we are going to talk about specific scenarios where it makes sense to use a map or a set now this video is going to be a continuation of episode 689 of syntax where Wes and Scott were chatting about maps and sets and specifically Wes was giving some examples of where he's using maps in his code so I'm going to show you some code examples today and kind of walk you
through the scenarios where it makes a lot of sense to use a map or a set versus an object I'm CJ welcome to [Music] syntax now let's say for example you have this books by ID object where all of the keys are the ID of the books and then all of the values are the books themselves you might have a function get book that accepts the ID and then just returns that book at that specific ID this will mostly work but what you might not have considered is there are certain things that are on the book object because it in from the object prototype and if we for example say get book and we pass in the string Constructor that's going to return the object Constructor and we don't want that um and so this is the reason you typically when you're doing this in a code base you actually see some guarded checks around this access so you might actually say if books by ID has owned property so this means does this object have this property and don't look up the Prototype chain and if it does then
The problem with Objects
we'll return that and in this scenario this will work but there are some scenarios where you can actually create an object that doesn't inherit from the object prototype and in that case it won't have the has own property method so you probably seen this in code bases as well where you have something like object. prototype so this grabs the has owned property method from the object prototype itself and then we want to call that on this specific object with that argument there so you probably have seen this somewhere in a code base before and the reason we do this is just to make sure that uh when we're checking for properties to exist we're only looking at the properties on the object itself not the Prototype chain now if you have code like this in your codebase this is probably a really good use case for a map now in your code base you probably don't have just a static object where all of the keys are already set like in your code this is probably dynamically constructed based on some API response like you get back a list of
When to use a Map
books and then you build out this object so that way you can easily look up books by ID if you're doing that it's a perfect use case for a map so let me show you how to use a map instead so to create a map we can use the map Constructor so let's say I have books by ID we'll say new map and now I have an instance of a map now there are a few methods on a map so for instance if we want to add something into the map we can say books by id. set we give it a key in this case I'll say the key is 42 and then we give it a value now this has added this specific book into the map with that key now if we want to get it out there's a couple of methods we can use so books by ID now has the has method and this will return true or false so if I pass in 42 it returns true because that exists on the map but if I pass in something that isn't in the map it's going to return false we can also get things out of the map so maps have the git method and we can pass in a specific key that'll give us back the thing if we pass in a key that isn't in
How to use Map
there it's going to give back undefined now Maps also support initializer syntax so instead of having to call set we actually can pass in an array of arrays where each array has keys and values let me show you what I mean so for this map we can pass in an array and then we can pass in a nested array where we have the key comma value and so this is a nice convenient way of in like initializing a map with a bunch of keys and values you basically just pass in these key value pairs this should work in the same way if we pass in 42 we're going to get back that specific book so let's actually construct this map using the book data that we had in the last example so we have this object the keys are the ID the values are the books themselves there is a built-in method on objects that will give us back an array of key and values and that's what we can use in the initializer syntax so if I here say books by ID map and then we try to create a map I can use object. entries pass in the existing object that we have
Create a Map from an Object
and this is going to give us back a map check it out however you will notice one thing the inferred key here is of type string and when I Define my object here we Define them as numbers so we think uh but that's that's not actually the case so when you define objects the keys are always strings no matter what so behind the scenes when this object got initialized all of these Keys even though I specified them as numbers they actually got coerced to Strings and so to see that in action if I pull out books by ID at the number 42 that gives me back Hitchhiker's Guide to the gxy but if I pass in the string 42 we get back the same thing and so this is actually one of the benefits of maps is that they will use a specific type for the key whereas objects can only use strings as the key and then you run into this scenario here so the fact is when I'm actually passing in a number behind the scenes it's coercing it to a string and so by default this isn't going to give us exactly what we want because we now have a map where the keys are
Object Keys are Strings
strings instead of numbers so I'm going to show you potentially what we should do instead and ideally we have an array that we then want to convert into a map because if we have that then we can choose whatever we want as the key and specifically use the the number value here for ID so let's say you have this array of books and you want to construct this map we can create an instance of the map and then again we need to pass in an array of key and values in this case we can just use the map method on arrays not to be confused with the map object itself so map is a method on arrays that will return a new array of the same length for a given given array so let's say we say books stop map this gives us each individual book but we want to turn this into an array that is a key in a value we can pass in book. ID and book and so the result of this is going to be an array where the first value is the ID the second value is the book but because we passed that whole thing into the map now you can see the inferred type has number as the key and
Create a Map from an Array
then a book as the actual value now whatever you end up doing whether it's a map or a for each or or reduce you're going to end up with a nice little map like this and what's cool about this is we actually don't even need a custom method like we did before so in the previous example we had this git book function which we needed to call in order to get access to the book because we had to have this little guard Clause here to make sure that this thing actually the ID actually existed on the books by ID object when you use a map you don't really need any wrapper methods because you can just use those built-in methods so here we can just say get the book with id4 to and you'll notice if we pass in a string we don't actually get back the book so it it is using the specific type we set as the key here and we don't run into the issue of prototype properties so I can't ask for the Constructor or the two string or or or anything like that now one of the gotchas of using Maps is the fact that they don't automatically serialize so let's say we were to do json. stringify on this map here you'll notice we just
Map methods are nice
JSON.stringify a Map
get back an empty object and the implementation here is completely up to you whether you're sending a map from your back end or you want to send a map to your backend ultimately the native JavaScript way of representing this is with key value pairs in an array right so what we can do is before we stringify it is just turn it into an array of keys and values so maps have this method on them called entries and that's an iterator so we need to spread it into an array here and so if we do this now when we stringify it we're going to get an array of arrays where each of the keys is the first value in the nested array and each object is the second value in that nested array and what's nice about serializing it in this way is it holds on to the type of the keys instead of like trying to turn it into an object and then stringifying the object I would recommend stringifying it using the entries here because then you can reconstruct it back into a map very easily because like I showed earlier you simply just pass in an array of arrays
to get back the map object now let's take a look at where you might use a set so a set actually comes from mathematics and it describes a collection of things and one of the unique features of a set is that it can only have unique values so you can think of a set kind of like an array but it does have that that property that only unique things can be put into that list or that collection and so let's look at this code example here or let's say you're trying to implement an add to cart function for like an online library or something like that so you might have your cart object you have your book IDs and this is each ID of the book that has been added to the cart and in this scenario a user can only check out one of a specific book you might have this is in cart method that takes in a book ID and then you want to check does that ID exist within that list of book IDs and in this case we're just using the includes method now this is fine but as this array starts to grow this includes method actually has to check every single value in the array and that's not ideal and this is kind of
Sets
The problem with Array.includes
like hiding the complexity here just by using the includes function in the same the same follows if you use like filter or find it literally has to iterate over the entire ire array so if we were to actually Implement kind of what's happening for includes it's it's literally a for Loop it actually has to iterate over the entire array here so let's say we implement it with a for Loop okay so we updated it to use a for Loop instead and now you can really see well oh yeah it has to literally look at every single value in that array to determine if it's in the cart and the code's going to work the same down here but I just kind of want to show you that when you use includes or filter or find you do have to think about the fact that it's searching over the entire array now with sets we don't have to search over an array like this and let me show you an example so to kind of take a step back let's actually look at how we would do this not with an array but even just with a built-in object so let's say we don't want to have to search an array every time if we instead convert this to an object so let's say I have book IDs and it's an object where all of the keys
Making a Set with an Object
are the ID and then the value is just true that yes this book is in in this this list here so at this point if I want to check check to see is the book ID already in the book ID's object uh we wouldn't use includes because this isn't an array we can just use object notation so I can say cart. book IDs at book ID so if it's in there it's going to return true if it's not in there it's going to return false now this will work and this actually is a constant time lookup because we're literally just checking to see does the property exist on this object and instead of using an array to search over it uh it's just a constant time lookup now we run into the same issue as we did earlier where if book ID is anything besides like an ID if it's like a string Constructor or the string two string or the string value of we could run into some issues here so again we're going to have to wrap this in a guard Clause to make sure that we're only looking at the properties of this this specific object but this would be one way of implementing it simply just using an
object but let's use a set so the API for sets is super simple and it actually accepts an array as an argument so if I create a new set here now we can use the has method of a set so instead of needing to search the array we can just say book IDs has that specific book ID and this method doesn't need to search the list it's able to actually have a constant time lookup to see is the thing in the list and so if you have this kind of code in your code base it's actually a really easy replacement to stop using includes just put that thing into a set instead of a plain old array and now you can start using the has method now one of the other aspects of sets that I mentioned is that they only allow unique values and so if I attempt to add the the same thing twice so let's just do cart book IDs we're going to add 42 again if we look at what's inside book IDs here you'll notice 42 is only in there once and uh you just get that for free on sets and so if you ever have some code where you're storing things in
Create a Set from an Array
Sets and Duplicate Values
an array and then you're checking to see well is it already in the array and if it is then don't add it with sets you don't even have to have that check anymore it's automatically going to D duplicate anything you put into the list now the there's a bunch of other methods on a set that you can use and like I mentioned sets come from mathematics and set theory and there's actually methods that allow you to perform set operations so you can do things like difference or intersection or Union so if you're doing mathy things in your codebase you can even get that benefit by by using sets as well but I highly recommend check out the mdn page you can see the other methods and and see the other types of things you can do with a set now after hearing me talk about those things hopefully you've identified some scenarios in your code base where you can use a map or a set instead and that's really all I want I'm not telling you to use maps everywhere or sets everywhere there are certain scenarios where it's going to be easier to use it's going to make your code easier to read and easier to maintain um and overall in some scenarios much more performant as well so like I said if you
Set methods on MDN
Thanks for watching
have not heard episode 689 of syntax definitely go check it out where Wes and Scott dive deeper into using maps and sets and when and where to use them that's all I have for you in this video if you found it useful if you've identified some scenarios where you use maps or sets let us know down in the comments also if there are things that I didn't talk about that you think people should know let us know down in the comments as well so yeah that's it I'll see you in the next [Music] one
Quote it with credit and a link. Quoting Syntax