Imagine the following scenario in JavaScript:
You’re building a contact management app, and you need to track data about contacts, but you need to allow your users to add custom data points for each contact in the system. So for one contact, you might track their name, age and birthday, but for another contact, you want to track their favorite holiday and the name of their dog.
How would you go about modeling this in your logic?
One possible answer would be a pair of arrays. The first array would contain the labels for each data point, and the other array would contain the values of each data point. But this is a bit unwieldy. Maybe a single array, where the even indexes have the label of the data, and the odd indexes have the value? So if data[0] equals “name” then data[1] would contain the contact’s name.
Again, this works, but it’s a bit….clunky.
An object is a much better choice, since it’s innately a key/value pair, and you can add keys & values to an existing object at runtime. You can do this by accessing and setting the properties of the object using the array indexer syntax.
Usually to get the name property of an object we do this:
but we can actually access that same property by doing this:
So now, we can add new properties with names defined by our users, by using a function like the following:
Check out an example of this here.
But there’s another option. The new ES6 datatype Map can offer the same functionality with possibly a bit more elegance. A map is like an object, in that it is a collection of key/value pairs, but instead of using an array syntax, Maps use set and get methods.
So the above function would now look like this:
See a running example here.
The Map object has a few advantages over a standard JavaScript object: it remembers insertion order, it’s a bit easier to iterate over, it has a length property, it supports datatypes other than strings as the key, and it’s easier to remove items from.
Knowing the different data types available, and their relative strengths & weaknesses can make a great deal of difference in your code.
Now if you really want to stretch your noggin, see if you can figure out what the following code would do:
And what if we added this?
Try it out in this stackblitz project here (open the console by clicking the word “console” in the bottom right).
Happy Coding!
Signup for my newsletter at here.
Visit Us: thinkster.io | Facebook: @gothinkster
| Twitter: @gothinkster
Top comments (0)