JavaScript:JavaScript Objects and Map: Key-Value Data Structures
JavaScript•Objects & Maps

JavaScript Objects and Map: Key-Value Data Structures

Compare Object literal key-value mapping with Map, which supports arbitrary key types and maintains insertion order.

Syntax

const obj = { key: "value" }; const map = new Map(); map.set(key, val);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
ObjectBuilt-in StructureString/Symbol keys; ideal for records and configurations.
MapES6 CollectionAllows any type of key (objects, functions, numbers); O(1) lookups.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// 1. Plain Object with Destructuring
const serverConfig = {
  host: "127.0.0.1",
  port: 8080,
  ssl: true
};

const { host, port } = serverConfig;
console.log("Server running at:", host + ":" + port);

// 2. ES6 Map with Non-String Keys
const cache = new Map();
const userObj = { id: 101 };

cache.set(userObj, { role: "admin", accessExpires: "2026-12-31" });
console.log("Has User:", cache.has(userObj));
console.log("Cached Role:", cache.get(userObj).role);
Expected Output:
Server running at: 127.0.0.1:8080
Has User: true
Cached Role: admin

How It Works: Step-by-Step

  • Lines 2-8: Defines object and extracts properties using ES6 destructuring.
  • Lines 11-15: Uses object reference userObj directly as a key in Map.

Key Concepts

  • Objects only support strings and Symbols as keys (other types are coerced to strings).
  • Map allows any type of key, including objects and functions.
  • Map has a built-in .size property, unlike Object where you must use Object.keys(obj).length.

Common Mistake: Using bracket notation on Map instead of .set() and .get()

map["key"] sets a property on the Map object instead of storing it inside the Map hash table.

❌ Incorrect
const m = new Map();
m["a"] = 1; // Does NOT store in Map!
console.log(m.get("a")); // undefined
✅ Correct
const m = new Map();
m.set("a", 1);
console.log(m.get("a")); // 1

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler