Get the length of a Map in JavaScript

You can use the size property to get the length of a Map object. The size property returns the number of elements in the Map object.

const map = new Map()

console.log(map.size) // 0

map.set('name', 'Atta')
map.set('age', 34)

console.log(map.size) // 2

The size property returns an integer value representing how many entries the Map object has.

Unlike the array's length property, the map's size property is read-only and can not be changed:

const map = new Map([
  ['name', 'Atta'],
  ['age', 34]

console.log(map.size) // 2

map.size = 6

console.log(map.size) // 2 --> Remains the same

This is not the case with the length property of the array, which is writeable and can be set to a new value to increase or decrease the size of the array:

const numbers = [1, 2, 3, 4]

// Truncate to 3-element
numbers.length = 3

// [1, 2, 3]

// Increase size to 5
numbers.length = 5

// [ 1, 2, 3, <2 empty items> ]

Read this article to learn more about the Map object and how to create collections of key-value pairs in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.