JavaScript Interview Question on Map Data Structure - Delete an element

We need to find the output of this code. mapping is variable that holds a JavaScript Object Map. And the contents of this map are some key value pairs. mapping.delete actually deletes an element from this map. And finally logs the value of mapping variable. Let’s look at what this code does.

Code

let mapping = new Map([[1, 2], [2, 3], [3, 4], [4, 5]])
mapping.delete(2)
console.log(mapping)

Full Transcript

00:00 This is a question on JavaScript Map and we need to find the output of this code. mapping is a variable that holds a JavaScript object Map and the contents of this map are some key value pairs, mapping.delete() actually deletes an element from this map and finally we log the value of mapping variable here. Let's look at what this code does. Map object is a data structure in JavaScript which contains the key value pairs. Now if the way this map is declared and initialized here looks a bit confusing, then the syntax on line 1 is equivalent to this code. Creating a variable called mapping and initialize an empty map object. Then using the set() method available on map with two arguments, a key and its corresponding value. In the above code, we used a shorthand where a map is created and initialized in a single line by passing an array of arrays, where each array contains a key and its corresponding value. Both result in the same map.

01:00 All right, so now our mapping variable looks like this.

01:03 mapping.delete(2) deletes the element from the map that has a key 2 and the resulting map has only these three elements left. So when we log the value of mapping variable, this should be the output. Let's run the code in our editor and here is exactly the output. If you would like to take your JavaScript knowledge to the next level and want to know and understand how browsers execute JavaScript and the role of event loop, check out our new course, which is live. I've added the link in the description below, and friends, keep learning and share your knowledge.