Object vs Map
Written byPhuoc Nguyen
Category
JavaScript
Created
10 Aug, 2020
Last updated
05 Feb, 2021
Storing the key and value pairs is a common thing we have to deal with in JavaScript. The most basic approach is to use an object:
const person = {};
person.name = 'Foo';
person.age = 20;
// Or
const person = {
name: 'Foo',
age: 20,
};
Being introduced from ES6, the
`Map`
data structure provides the same ability. The sample code above can be rewritten with `Map`
as following:const person = new Map();
person.set('name', 'Foo');
person.set('age', 20);
#Differences
-
Object only accepts string and symbol keys. Another types will be converted to string automatically.
`Map`
on the other hand accepts any type of key. -
We can iterate over the properties of a
`Map`
directly using`forEach`
or`for ... of`
statement:const styles = new Map();styles.set('color', 'blue');styles.set('fontSize', '12px');styles.forEach((value, key) => console.log(key, '=', value));// Output:// color = blue// fontSize = 12pxObjects are not iterable directly. In order to loop over the properties of an object, we have to use either`Object.keys`
,`Object.values`
or`Object.entries`
to receives the list of keys, values or pairs of key and value.styles = {color: 'blue',fontSize: '12px',};Object.keys(styles).forEach((key) => console.log(key, '=', styles[key]));// Output:// color = blue// fontSize = 12px -
Object have special properties such as
`constructor`
,`__proto__`
, etc.let person = {};person['constructor']; // ƒ Object() { [native code] }While`Map`
only consists of what we define:let person = new Map();person.get('constructor'); // undefined -
JSON supports
`Object`
:const person = {};person.name = 'Foo';person.age = 20;JSON.stringify(person); // "{"name":"Foo","age":20}"With`Map`
, it's not possible to get the proper data when being serialized with JSON:const person = new Map();person.set('name', 'Foo');person.set('age', 20);JSON.stringify(person); // "{}"
#Good to know
Maps keep the order of items. It means when you loop over keys of a map, we will see the same order as when they're inserted to the map.
It's true for objects that only consists of string and symbol keys. The order of object's keys aren't kept if there is a key that needs to be converted to string.
let codes = { A: 65, B: 66, C: 67, 0: 48 };
codes; // {0: 0, A: 65, B: 66, C: 67}
Object.keys(codes); // ["0", "A", "B", "C"]
#Good practice
If we want to store the key/value pairs without caring about serializing them in JSON, then use
`Map`
.
Looping through and getting the size of a map is more comfortable than doing with an object.`Object`
should be used if we want to convert back and forth between raw data and JSON, or include a specific business logic:const person = {
firstName: 'Foo',
lastName: 'Bar',
getFullName: function () {
return `\${this.firstName} \${this.lastName}`;
},
};
#See also
Questions? 🙋
Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.
Recent posts ⚡
Copy the content of an element to your clipboard
01 Oct, 2023
Make a text area fit its content automatically
30 Sep, 2023
Quickly insert alternate characters while typing
30 Sep, 2023
Zebra-like background
30 Sep, 2023
Add autocomplete to your text area
28 Sep, 2023
Linear scale of a number between two ranges
28 Sep, 2023
Highlight the current line in a text area
27 Sep, 2023
Create your own custom cursor in a text area
27 Sep, 2023
Mirror a text area for improving user experience
26 Sep, 2023
Display the line numbers in a text area
24 Sep, 2023
Select a given line in a text area
24 Sep, 2023
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn