Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Maps in JavaScript

Js Maps in JavaScript

?? JavaScript Maps

A Map in JavaScript is a collection of key-value pairs where:

  • Keys can be any data type (objects, functions, primitives)

  • Keys maintain the insertion order

  • Maps are iterable


Why use a Map instead of a plain object?

  • Objects only allow strings and symbols as keys

  • Maps allow any type as a key (e.g., objects, functions)

  • Maps have a size property (easy to get the number of entries)

  • Maps are designed specifically for mapping key-value pairs with useful built-in methods


Creating a Map

const map = new Map();

Or initialize with an array of key-value pairs:

const map = new Map([  ['name', 'Alice'],  ['age', 25]]);

Basic Operations

const map = new Map();// Add entriesmap.set('name', 'Bob');map.set(42, 'The answer');map.set(true, 'Yes');// Get valuesconsole.log(map.get('name'));  // Bobconsole.log(map.get(42));      // The answer// Check if key existsconsole.log(map.has(true));    // true// Size of mapconsole.log(map.size);         // 3// Delete an entrymap.delete(42);// Clear all entries// map.clear();

Iterating over a Map

for (const [key, value] of map) {  console.log(`${key} => ${value}`);}

Map vs Object

FeatureMapObject
Key typesAny typeStrings and Symbols only
OrderMaintains insertion orderNot guaranteed
Size propertyYes (map.size)No (need to compute)
IterationDirectly iterableUse Object.keys() etc.
PerformanceOptimized for frequent add/removeNot optimized for map-like use

Want a practical example using Maps, or help converting Maps to arrays/objects?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql