JavaScript Map vs Object

Mehvish Ashiq Oct 12, 2023
  1. Define Map in JavaScript
  2. Define Object in JavaScript
  3. Code Example of a Map in JavaScript
  4. Code Example of an Object in JavaScript
JavaScript Map vs Object

This tutorial is about maps and objects in JavaScript, where we’ll compare both of them and learn how to use each of them.

Define Map in JavaScript

JavaScript Map is a data structure that stores the data in key-value pair form. It remembers the key’s original order of insertion.

Map avoids duplicity because each pair has a unique key and a value mapped to this particular key. The key can be any value, including primitive, object, and function.

The map is iterable, so we can iterate over the elements using the for...of loop.

Define Object in JavaScript

Objects also store the data in key-value pair form, just like the map. Each key-value pair is known as a property in the object.

Objects’ keys can only be a string type. If you use a number as a key in an Object, it would be converted to a string.

Objects are not iterable until they use iterable protocol.

Now we’ve got a basic understanding of Map and Object. Let’s compare them by using a table to make the concept clear.

S# JavaScript Map JavaScript Object
1 Map is known as an instance of an object. Object is not an instance of Map.
2 Map holds the original order of insertion. Object does not preserve the original order of insertion.
3 The type of key can be any value, including String, Object, functions, etc. The type of key can only be of String type.
4 We can quickly access the map’s size by using the following code: <br />map.size Manual computation is needed to find the size of the object using the following code: <br />Object.keys(obj).length
5 Map are iterable, can be done using for...of loop as follows: <br />for (const m of map){<br /> console.log(m);<br />} Objects are not iterable, we have to hold object’s keys to traverse. <br />Object.keys(obj).forEach(key => {<br /> console.log(key, obj[key]);<br />}
6 No default keys. Objects can inherit keys from the prototype.
7 We have to write a custom parser to convert Map into JSON String. Objects can use JSON.stringify to convert into JSON String.

Code Example of a Map in JavaScript

JavaScript Code:

const map = new Map();                    // create map
const keyOfStringType = 'string';         // make a key of string type
const keyOfObjectType = {};               // make a key of object type
const keyOfFunctionType = function() {};  // make the function a key

// setting the values with all tpes of keys
map.set(keyOfStringType, 'String Value');
map.set(keyOfObjectType, 'Object Value');
map.set(keyOfFunctionType, 'function Value');

// check if the map is an instance of object
console.log(map instanceof Object);

// map size
console.log('Map Size: ' + map.size);

// get value of key `keyofStyingType`
console.log('Value at key named keyOfStringType: ' + map.get(keyOfStringType));

// iterate over the map elements
console.log('Iterate over the Map elements');
for (const m of map) {
  console.log(m);
}

Output:

true
"Map Size: 3"
"Value at key named keyOfStringType: String Value"
"Iterate over the Map elements"
["string", "String Value"]
[{ ... }, "Object Value"]
[function() {}, "function Value"]

Code Example of an Object in JavaScript

Objects can be created in three ways that are listed below.

Create JavaScript Object By Using String Literal:

let person = {name: 'Mehvish Ashiq', city: 'Lahore', email: 'mehvish@yahoo.com'}

Create JavaScript Object By Creating An Instance of Object:

const person = new Object();  // we used this method in this tutorial

Create JavaScript Object With Object Constructor:

function person(name, city, email) {
  this.name = name;
  this.city = city;
  this.email = email;
}
let p = new person('Mehvish Ashiq', 'Lahore', 'delfstack@example.com');

You can find more about Objects here. Let’s practice with the startup code now.

JavaScript Code:

// create object using instance of object
const person = new Object();
// set the properties and values
person.firstname = 'Mehvish';
person.lastname = 'Ashiq';
person.age = 30;
person.showInfo =
    function() {
  console.log(
      `${person.firstname} ${person.lastname} is ${person.age} years old`);
}

    // check if an object named person is an instance of Map
    console.log(person instanceof Map);

// object size
console.log('Object Size: ' + Object.keys(person).length);

// get value of key `firstname`
console.log('Value at key named firstname: ' + person.firstname);

// get all keys
console.log('Object Keys: ' + Object.keys(person));

// get all values
console.log('Object Values: ' + Object.values(person));

// iterate over the person object elements
console.log('Iterate over the person object elements');
Object.keys(person).forEach(key => {
  console.log(key, person[key]);
});

Output:

false
"Object Size: 4"
"Value at key named firstname: Mehvish"
"Object Keys: firstname,lastname,age,showInfo"
"Object Values: Mehvish,Ashiq,30,function(){
 console.log(`${person.firstname} ${person.lastname} is ${person.age} years old`);
}"
"Iterate over the person object elements"
"firstname", "Mehvish"
"lastname", "Ashiq"
"age", 30
"showInfo", function(){
 console.log(`${person.firstname} ${person.lastname} is ${person.age} years old`);
}
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Object