Dicts vs Objects and Map
Key-value structures in JavaScript
Introduction
In this lesson, you'll learn about dicts vs objects and map in JavaScript. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with key-value structures in javascript.
JavaScript has its own approach to key-value structures in javascript, which we'll explore step by step.
The JavaScript Way
Let's see how JavaScript handles this concept. Here's a typical example:
const person = { name: "Alice", age: 30 };
// Access
console.log(person.name); // dot notation
console.log(person.city ?? "Unknown"); // nullish coalescing
// Mutate
person.city = "Istanbul";
delete person.age;
// Iteration
for (const [key, val] of Object.entries(person)) {
console.log(key, val);
}
// Merge
const merged = { ...person, role: "admin" };
// Map – better for dynamic keys
const map = new Map();
map.set("key", 123);
map.get("key"); // 123
map.has("key"); // trueComparing to Python
Here's how you might have written similar code in Python:
person = {"name": "Alice", "age": 30}
# Access
print(person["name"])
print(person.get("city", "Unknown"))
# Mutate
person["city"] = "Istanbul"
del person["age"]
# Iteration
for key, val in person.items():
print(key, val)
# Merge (Python 3.9+)
merged = {**person, "role": "admin"}
# Dict from keys
squares = {n: n**2 for n in range(5)}You may be used to different syntax or behavior.
JS objects allow dot notation (obj.key); Python dicts don't
You may be used to different syntax or behavior.
Object.entries() ≈ dict.items()
You may be used to different syntax or behavior.
JS Map for dynamic/non-string keys — closer to Python dict
You may be used to different syntax or behavior.
{...obj} spread ≈ {**dict} unpacking
Step-by-Step Breakdown
1. Property Access
JavaScript objects support both dot (obj.key) and bracket (obj['key']) notation.
person["name"]
person.get("city", "Unknown")person.name
person["name"]
person.city ?? "Unknown" // nullish coalescing2. Iteration
Object.entries() returns [key, value] pairs, just like dict.items().
for key, val in d.items(): ...for (const [key, val] of Object.entries(obj)) { ... }3. When to Use Map
Use Map when you have dynamic/non-string keys or need guaranteed insertion order.
d = {} # Python dicts maintain insertion order (3.7+)// Object: string keys only (mostly)
const map = new Map(); // any key type, orderedCommon Mistakes
When coming from Python, developers often make these mistakes:
- JS objects allow dot notation (obj.key); Python dicts don't
- Object.entries() ≈ dict.items()
- JS Map for dynamic/non-string keys — closer to Python dict
Key Takeaways
- Dot notation available in JS (no Python equivalent)
- Object.entries() ≈ dict.items()
- Use Map for dynamic keys / when key type matters