The Problem With Objects
You’re deep into your code, and suddenly you get an error: “Cannot read property x of undefined.” Awww, man.
Most of the time, this means debugging — attacking my code with
console.log() there. Most of the time, I get it fixed fast. But there are those days that it takes me hours.
We have an object called
The car object has a set of key-value pairs. We get this information from our API. Normally, you’d get an
events property inside the object that includes the property
last_updated — stating the last time this information has been changed.
When running this code, we get an error.
Uncaught TypeError: Cannot read property 'last_updated' of undefined at <anonymous>:1:14
To prevent the error, we have to check if the property
events is in the object or not.
This way, we don’t have an error if the
event property is not in our object. But I find this code to be not that readable.
The Map Solution
When we turn our object into a
Map(), we get all the clear methods from the map.
You can turn your object into a map with the
Object.entries() method and give it your object as a parameter.
This would be the output of the map.
Map() has a range of handy methods we can use to make our code more readable, predictable, and with fewer chances for getting errors.
set('key', 'value')store a key-value pair
get('key')returns the value of a key if available
falsedepending on if the key exists
delete('key')deletes a key-value pair from the map
clear()removes all the key-value pairs from the map
size()returns the amount of key-value pairs from the map
So if we want to have the information
last_updated from the
events the property, we use the
.has('prop') method. This method returns a boolean based on the existence of the property.
In your console, you’ll see the console logged
‘not available’ without any errors.
As already a few other helpful developers showed in the comments. The Map isn’t maybe the best solution for every problem for making your Objects more predictable.
Still, I think it could be an interesting solution 😉
I think using
Map() can make your code more readable, predictable, and less sensitive to errors. With the normal
Object, your code will give errors when a certain property is missing. This will lead to bad user experience, so let's prevent this.
If you want to check out more details about
Map(), please check out the detailed page of MDN web docs.
I hope you learned something new with this piece. Happy coding!