Course contentsShow
← JavaScript
Lesson 1032 of 2,72324. Maps and SetsFree lesson

Creating a New Map

Using the Map constructor with or without an iterable of key-value pairs.

Creating a New Map

You'll learn: How to create a new Map using the Map constructor, either empty or initialized with key-value pairs.

The Basics

Creating a Map is straightforward. You use the Map constructor, which can be called in two ways:

  1. Empty Map: Call new Map() with no arguments to create an empty Map that you'll populate later.
  2. Initialized Map: Pass an iterable of [key, value] pairs (typically an array of arrays) to create a Map with initial entries.

Think of it like setting up a filing cabinet—you can start with empty drawers and add folders later, or you can install it pre-loaded with labeled folders.

Creating an Empty Map

const myMap = new Map();
console.log(myMap.size); // 0

Creating a Map with Initial Data

When you have data ready, pass an array of [key, value] pairs:

const userRoles = new Map([
  ['alice', 'admin'],
  ['bob', 'editor'],
  ['charlie', 'viewer']
]);

console.log(userRoles.size); // 3

Each inner array represents one entry: the first element is the key, the second is the value.

Why the Array-of-Arrays Format?

The Map constructor accepts any iterable of key-value pairs. Arrays are the most common choice, but this format makes it easy to convert between Maps and other structures later.

const settings = new Map([
  ['theme', 'dark'],
  ['fontSize', 16],
  [true, 'boolean key works!']
]);

Key Takeaway: Create a Map with new Map() for an empty Map, or pass an array of [key, value] pairs to initialize it with data immediately.