Ad space (banner)
🟨JavaScript Lessons
Lesson 53 / 69

The Basics of Map (an Object for Key-Value Pairs)

In this lesson you'll learn the basics of JavaScript's Map object, so you can understand a more capable way of handling key-value pairs than a plain object. This is for people searching "JavaScript Map usage" or "JavaScript Map vs Object."

A Map is a mechanism for storing "keys and values" just like an object, but it comes with features that are more convenient to work with — the insertion order of keys is preserved, and you can check whether a key exists with has(). You add with .set(key, value), retrieve with .get(key), and check existence with .has(key).

The sample code registers scores in a Map called scores, using names as keys, retrieves a value with .get("Alice"), and checks a key that doesn't exist with .has("Charlie"). When looping over every entry with .forEach((value, key) => { ... }), notice that the order of the value and key arguments is a bit different from how you'd do this with an object.

A common beginner stumbling block is that, to check the size of a Map, you use a property called .size, not an array's .length. Since the API differs slightly from objects and arrays, it can feel unfamiliar at first, but Map is often easier to work with than objects in real projects when you need to check for key existence or get the size.

Map is often better suited than an object when you want to use something other than a string as a key (like a number or object), or when you need to efficiently work with a large amount of data. It's worth remembering as an option for when you want to efficiently manage a large volume of data.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)