JavaScript Interview Question #49
What are Map and Set in JavaScript?
Objects, Arrays & Core Data Handling Junior Beginner
Quick Interview Answer
Map is a key-value collection whose keys can be values of any type. Set is a collection of unique values. Both are iterable and provide dedicated methods such as set, get, has, add, and delete.
Detailed Explanation
Map is a key-value collection whose keys can be values of any type. Set is a collection of unique values. Both are iterable and provide dedicated methods such as set, get, has, add, and delete.
Map is often preferable when the data is conceptually a dynamic key-value collection rather than a record-like object. Set is useful for uniqueness checks and removing duplicate primitive values.
Code Example
const roles = new Map();
roles.set(1, "Admin");
roles.set(2, "User");
console.log(roles.get(1)); // Admin
const numbers = [1, 1, 2, 3, 3];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3]