How to check if a Map has a key in JavaScript

Checking for the existence of a key in a Map is essential for avoiding errors and writing defensive code in JavaScript applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented key existence checks countless times across 25 years of JavaScript development. The most reliable method is using the has() method, which returns a boolean indicating whether the key exists in the Map. This approach is clean, performant, and the standard way to verify key presence in modern JavaScript.

Use the has() method to check if a key exists in a Map.

const settings = new Map([
  ['theme', 'dark'],
  ['language', 'en']
])

const hasTheme = settings.has('theme')
const hasColor = settings.has('color')

Here the has() method is called with the key to check. It returns true if the key exists in the Map and false if it doesn’t. This allows you to safely verify key existence before attempting to retrieve or modify values, preventing unexpected undefined returns.

Best Practice Note:

This is the same approach we use in CoreUI to validate configuration keys before applying settings. Always use has() for conditional logic based on key existence rather than checking if get() returns undefined, as undefined could also be a legitimate stored value.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author