JavaScript objects, collections and iteration
Plain objects and arrays carry most data in JavaScript, but ECMAScript 2015 added a toolkit around them that every experienced developer should know. Object.assign copies properties, symbols create keys that cannot collide, proxies intercept operations on an object, Map and Set are real keyed collections, their weak variants attach data to objects without keeping them alive, and the iteration protocols with generators let any object work with for...of, spread and destructuring.
This page explains those features in that order, with one runnable sample per feature from an invented OrdersPortal application. It assumes you know objects, arrays and prototypes.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23. Two samples use ECMAScript 2025 additions (the new Set methods and iterator helpers), which Node.js 22 already supports.
Topics on this page
Section titled “Topics on this page”| Feature | Edition | Use it when |
|---|---|---|
| Object assign | ES2015 | You copy properties into an existing object, running its setters. |
| Symbols | ES2015 | You need a property key that cannot clash, or a protocol hook such as Symbol.iterator. |
| Proxy | ES2015 | You intercept reads, writes or calls for validation, logging or virtual objects. |
| Map and Set | ES2015, Set methods ES2025 | You need keyed lookups with any key type, or unique values. |
| WeakMap and WeakSet | ES2015 | You attach data to objects you do not own without keeping them alive. |
| Iterators | ES2015, helpers ES2025 | You make a custom object work with for...of, spread and destructuring. |
| Generators | ES2015 | You produce a sequence lazily, one value at a time. |
Object assign
Section titled “Object assign”Introduced in ECMAScript 2015. Object.assign(target, ...sources) copies the own enumerable properties, with both string and symbol keys, from each source onto the target, left to right, and returns the target. Later sources overwrite earlier ones. null and undefined sources are skipped.
It copies by getting each source value (so source getters run and their result is copied as a plain value) and setting it on the target (so target setters run). That is the key difference from object spread { ...a, ...b }, which always creates a new object and defines properties without calling setters. Object.assign therefore fits two jobs: updating an existing object in place, such as applying changes to a model that validates through setters, and older code that predates spread (ES2018).
The copy is shallow: nested objects are shared, not cloned. Non-enumerable and inherited properties are ignored. If writing a property throws, for example because the target property is read-only, the copy stops part-way and the properties already written stay written.
const defaults = { currency: "EUR", pageSize: 25, filters: { status: "all" } };const saved = { pageSize: 50 };const settings = Object.assign({}, defaults, saved, null, { theme: "dark" });console.log(settings);console.log("nested object shared:", settings.filters === defaults.filters);
class Order { #qty = 1; get qty() { return this.#qty; } set qty(value) { if (!Number.isInteger(value) || value < 1) throw new RangeError(`Invalid qty: ${value}`); this.#qty = value; }}
const order = new Order();Object.assign(order, { qty: 3 }); // runs the setterconsole.log("qty via setter:", order.qty, "| still an Order:", order instanceof Order);
const spreadCopy = { ...order, qty: 0 }; // plain object, no setter, no validationconsole.log("spread copy:", spreadCopy, spreadCopy instanceof Order);
try { Object.assign(order, { qty: 0 });} catch (error) { console.log(error.name + ":", error.message);}
const record = Object.defineProperty({ note: "" }, "id", { value: "A-1001", enumerable: true }); // read-only idtry { Object.assign(record, { note: "gift", id: "X", total: 5 });} catch (error) { console.log(error.name + ":", error.message); console.log("partly copied:", record); // note was written, total was not}Output:
{ currency: 'EUR', pageSize: 50, filters: { status: 'all' }, theme: 'dark'}nested object shared: trueqty via setter: 3 | still an Order: truespread copy: { qty: 0 } falseRangeError: Invalid qty: 0TypeError: Cannot assign to read only property 'id' of object '#<Object>'partly copied: { note: 'gift', id: 'A-1001' }Pitfalls:
- Mutating the first argument by accident.
Object.assign(defaults, saved)changesdefaultsfor every later caller. Pass{}first, or use spread. - Expecting a deep merge. Nested objects are replaced or shared, never merged. Merge nested levels explicitly or use
structuredClonefor copies. - Merging untrusted input. Copying a request body into a stored record lets clients set any field. Copy an allow-list of fields instead.
Symbols
Section titled “Symbols”Introduced in ECMAScript 2015. A symbol is a primitive value that is unique: Symbol("id") !== Symbol("id"). The optional text is only a description for debugging, readable as sym.description (ES2019). Symbols are mainly used as property keys that cannot clash with string keys or with keys added by other code, which makes them useful for attaching metadata to objects you share with libraries.
Symbol-keyed properties are skipped by Object.keys, for...in and JSON.stringify, but they are not private: Object.getOwnPropertySymbols and Reflect.ownKeys list them. Symbol.for("key") returns a symbol from a global registry shared across the whole runtime (and across realms such as iframes), so the same key always gives the same symbol.
Well-known symbols are hooks into the language. Symbol.iterator makes an object iterable, Symbol.asyncIterator makes it async-iterable, Symbol.toPrimitive controls conversion to numbers and strings, and Symbol.toStringTag changes the [object ...] tag. Symbols are not converted to strings implicitly: `${sym}` and sym + "" throw a TypeError; use String(sym) or sym.description. Symbol() cannot be called with new.
const auditInfo = Symbol("auditInfo");
const order = { id: "A-1001", total: 37 };order[auditInfo] = { createdBy: "import-job", at: "2026-11-02" };
console.log(Object.keys(order), JSON.stringify(order));console.log(Object.getOwnPropertySymbols(order), order[auditInfo].createdBy);console.log(Symbol("id") === Symbol("id"), Symbol.for("orders.id") === Symbol.for("orders.id"));console.log(auditInfo.description, Symbol.keyFor(Symbol.for("orders.id")));
class Money { constructor(cents, currency) { this.cents = cents; this.currency = currency; } [Symbol.toPrimitive](hint) { return hint === "number" ? this.cents / 100 : `${(this.cents / 100).toFixed(2)} ${this.currency}`; } get [Symbol.toStringTag]() { return "Money"; }}const price = new Money(3700, "EUR");console.log(`${price}`, +price * 2, Object.prototype.toString.call(price));
try { console.log(`key: ${auditInfo}`);} catch (error) { console.log(error.name + ":", error.message);}Output:
[ 'id', 'total' ] {"id":"A-1001","total":37}[ Symbol(auditInfo) ] import-jobfalse trueauditInfo orders.id37.00 EUR 74 [object Money]TypeError: Cannot convert a Symbol value to a stringPitfalls:
- Treating symbols as private. Anyone can list them with
Reflect.ownKeys. Use#privatefields for real privacy. - Expecting symbol keys in JSON.
JSON.stringifydrops them. Serialize such metadata explicitly. - Interpolating a symbol. Template literals throw. Use
sym.description.
Introduced in ECMAScript 2015. new Proxy(target, handler) creates an object that forwards every operation to target, except those the handler intercepts with traps. There are 13 traps, one for each internal object operation: get, set, has, deleteProperty, ownKeys, getOwnPropertyDescriptor, defineProperty, getPrototypeOf, setPrototypeOf, isExtensible, preventExtensions, and, for function targets, apply and construct.
Inside a trap, use the matching Reflect method to perform the default behavior, passing the receiver through, so that getters, setters and inheritance keep working. A set trap must return true for success; returning false makes the assignment throw a TypeError in strict mode.
The engine enforces invariants: a trap cannot lie about non-configurable or non-extensible state, for example by reporting a different value for a non-writable, non-configurable property. Proxy.revocable() returns a proxy you can switch off, which is useful for handing out temporary access.
Typical uses are validation, change tracking, logging, default values and API clients that build calls from property names. A proxy is a different object from its target (proxy !== target), and it does not forward private fields: calling a class method that reads this.#field through a proxy throws a TypeError. Proxies also add overhead to every intercepted operation, so keep them out of hot loops.
function trackChanges(target, log) { return new Proxy(target, { set(obj, prop, value, receiver) { if (prop === "qty" && (!Number.isInteger(value) || value < 1)) { throw new RangeError(`qty must be a positive integer, got ${value}`); } log.push(`${String(prop)}: ${JSON.stringify(obj[prop])} -> ${JSON.stringify(value)}`); return Reflect.set(obj, prop, value, receiver); }, deleteProperty(obj, prop) { log.push(`deleted ${String(prop)}`); return Reflect.deleteProperty(obj, prop); }, get(obj, prop, receiver) { if (typeof prop === "string" && !(prop in obj)) return `(no ${prop})`; return Reflect.get(obj, prop, receiver); }, });}
const changes = [];const line = trackChanges({ sku: "MUG-01", qty: 1, note: "" }, changes);line.qty = 3;line.note = "gift wrap";delete line.note;console.log(line.qty, line.color, changes);
try { line.qty = 0;} catch (error) { console.log(error.name + ":", error.message);}
const { proxy, revoke } = Proxy.revocable({ id: "A-1001" }, {});console.log(proxy.id);revoke();try { proxy.id;} catch (error) { console.log(error.name + ":", error.message);}
class Cart { #items = []; count() { return this.#items.length; }}try { new Proxy(new Cart(), {}).count();} catch (error) { console.log(error.name + ":", error.message);}Output:
3 (no color) [ 'qty: 1 -> 3', 'note: "" -> "gift wrap"', 'deleted note' ]RangeError: qty must be a positive integer, got 0A-1001TypeError: Cannot perform 'get' on a proxy that has been revokedTypeError: Cannot read private member #items from an object whose class did not declare itPitfalls:
- Forgetting
Reflectand the receiver.obj[prop] = valueinsidesetskips inherited setters and breaks subclasses. Forward withReflect.set(obj, prop, value, receiver). - Proxying class instances with private fields. Methods run with
thisset to the proxy, which has no private fields. Proxy plain data, or bind methods to the target. - Identity checks. A
SetorWeakMapkeyed by the target will not find the proxy. Decide which object your code passes around.
Map and Set
Section titled “Map and Set”Introduced in ECMAScript 2015. A Map stores key-value pairs where keys can be any value, including objects and functions; a Set stores unique values. Both keep insertion order when iterated, have a size property, and compare keys with SameValueZero, which is like === except that NaN equals NaN. Objects are compared by reference: two different objects with the same content are two different keys.
Prefer a Map over a plain object when keys come from data (customer IDs, SKUs), when you add and delete often, or when keys are not strings. A plain object has inherited keys such as toString and constructor, and string keys only. Map.groupBy (ES2024) groups items into a Map.
A Set removes duplicates ([...new Set(list)]) and answers membership questions quickly with has. ECMAScript 2025 added set algebra: union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom, each returning a new Set or a boolean.
Neither collection serializes to JSON directly: JSON.stringify(new Map(...)) gives {}. Convert with Object.fromEntries(map) or [...map] first.
const orders = [ { id: "A-1", customer: "C-7", status: "paid", skus: ["MUG-01", "TEE-03"] }, { id: "A-2", customer: "C-9", status: "pending", skus: ["MUG-01"] }, { id: "A-3", customer: "C-7", status: "paid", skus: ["CAP-07", "MUG-01"] },];
const ordersByCustomer = new Map();for (const order of orders) { const list = ordersByCustomer.get(order.customer) ?? []; list.push(order.id); ordersByCustomer.set(order.customer, list);}console.log(ordersByCustomer, ordersByCustomer.size, ordersByCustomer.get("C-7"));
const byStatus = Map.groupBy(orders, (order) => order.status);console.log([...byStatus.keys()], byStatus.get("paid").length);
const skusSold = new Set(orders.flatMap((order) => order.skus));console.log(skusSold, skusSold.has("CAP-07"));
const featured = new Set(["MUG-01", "LAMP-02"]);console.log("both:", skusSold.intersection(featured), "| featured unsold:", featured.difference(skusSold));
const objKey = { id: "C-7" };const cache = new Map([[objKey, "found by reference"]]);console.log(cache.get(objKey), cache.get({ id: "C-7" }), new Set([NaN, NaN]).size);console.log(JSON.stringify(ordersByCustomer), JSON.stringify(Object.fromEntries(ordersByCustomer)));Output:
Map(2) { 'C-7' => [ 'A-1', 'A-3' ], 'C-9' => [ 'A-2' ] } 2 [ 'A-1', 'A-3' ][ 'paid', 'pending' ] 2Set(3) { 'MUG-01', 'TEE-03', 'CAP-07' } trueboth: Set(1) { 'MUG-01' } | featured unsold: Set(1) { 'LAMP-02' }found by reference undefined 1{} {"C-7":["A-1","A-3"],"C-9":["A-2"]}Pitfalls:
- Using bracket access on a
Map.map["C-7"] = xsets an ordinary property, not an entry. Usegetandset. - Object keys by content.
map.get({ id: 1 })never finds an entry set with a different object. Use a primitive key such as the ID string. - Serializing directly.
JSON.stringify(map)is{}. Convert to an object or array of entries.
WeakMap and WeakSet
Section titled “WeakMap and WeakSet”Introduced in ECMAScript 2015. A WeakMap is a map whose keys are held weakly: an entry does not keep its key alive, so when nothing else references the key object, the garbage collector can remove the object and its entry. A WeakSet does the same for a set of objects. Keys must be objects or, since ECMAScript 2023, non-registered symbols; primitives and symbols from Symbol.for are rejected with a TypeError.
Because entries can disappear at any time, weak collections are not iterable and have no size or clear. You can only get, set, has and delete with a key you already hold. That restriction is the point: they are for attaching data to objects owned by someone else, such as:
- caching a computed result per object (an order’s tax breakdown) without leaking memory when the order is discarded;
- marking objects as processed or validated without adding properties to them;
- storing per-object private data in code written before
#privatefields existed.
If you need to observe that an object was collected, that is a different tool: WeakRef and FinalizationRegistry (ES2021), whose timing is deliberately unpredictable.
const taxCache = new WeakMap();let computeCount = 0;
function taxFor(order) { if (taxCache.has(order)) return taxCache.get(order); computeCount++; const tax = Math.round(order.total * 0.23 * 100) / 100; taxCache.set(order, tax); return tax;}
let order = { id: "A-1001", total: 120 };console.log(taxFor(order), taxFor(order), "computed", computeCount, "time(s)");
const validated = new WeakSet();validated.add(order);console.log("validated:", validated.has(order), validated.has({ id: "A-1001", total: 120 }));
order = null; // the cache entry no longer keeps the order alive and can be collected
console.log("size:", taxCache.size, "| iterable:", typeof taxCache[Symbol.iterator]);
const tag = Symbol("session");taxCache.set(tag, "symbols work as keys");console.log(taxCache.get(tag));
for (const key of ["A-1001", Symbol.for("shared")]) { try { taxCache.set(key, 1); } catch (error) { console.log(error.name + ":", error.message); }}Output:
27.6 27.6 computed 1 time(s)validated: true falsesize: undefined | iterable: undefinedsymbols work as keysTypeError: Invalid value used as weak map keyTypeError: Invalid value used as weak map keyPitfalls:
- Expecting to list or count entries. Weak collections cannot be enumerated. Keep a regular
Mapif you need to iterate. - Using primitive keys. Strings and numbers are rejected. Key by the object itself, or use a
Mapwith an eviction policy. - Relying on garbage collection timing. You cannot tell when an entry disappears, so never use weak collections for business logic that must happen at a known time.
Iterators
Section titled “Iterators”Introduced in ECMAScript 2015. Iteration in JavaScript is defined by two small protocols:
- An iterator is an object with a
next()method that returns{ value, done }. Optionally it hasreturn(), called when a loop exits early, for clean-up. - An iterable is an object with a
[Symbol.iterator]()method that returns a fresh iterator.
Everything that consumes sequences uses these protocols: for...of, spread [...x], array destructuring, Array.from, new Map(entries), Promise.all and yield*. Arrays, strings (by code point), Map, Set, typed arrays and arguments are built-in iterables. Plain objects are not; iterate them with Object.entries(obj).
Making your own class iterable lets callers use it like a built-in collection without exposing its internal array. Return a new iterator from each [Symbol.iterator]() call so the object can be iterated more than once.
ECMAScript 2025 added iterator helpers: built-in iterators inherit from Iterator.prototype, which now has lazy map, filter, take, drop and flatMap, plus reduce, toArray, forEach, some, every and find. A hand-written iterator object such as the one below does not inherit from Iterator.prototype, so wrap it, or the iterable that produces it, with Iterator.from() to get the helpers. They process one value at a time, without building intermediate arrays.
class OrderBook { #orders = []; add(order) { this.#orders.push(order); return this; } [Symbol.iterator]() { let index = 0; const orders = this.#orders; return { next: () => (index < orders.length ? { value: orders[index++], done: false } : { value: undefined, done: true }), return: () => { console.log(" (iterator closed early)"); return { value: undefined, done: true }; }, }; }}
const book = new OrderBook() .add({ id: "A-1", total: 120 }) .add({ id: "A-2", total: 15 }) .add({ id: "A-3", total: 64 });
for (const order of book) { if (order.total < 20) break; // calls return() console.log("for...of:", order.id);}
const [first, ...others] = book;console.log("destructured:", first.id, others.length, "| spread twice:", [...book].length, [...book].length);
const manual = book[Symbol.iterator]();console.log(manual.next(), manual.next().value.id);
console.log("plain iterator has helpers:", typeof book[Symbol.iterator]().filter);const bigIds = Iterator.from(book).filter((o) => o.total > 50).map((o) => o.id).toArray();console.log("iterator helpers:", bigIds);console.log(Iterator.from(new Set(["MUG-01", "TEE-03", "CAP-07"]).values()).take(2).toArray());Output:
for...of: A-1 (iterator closed early)destructured: A-1 2 | spread twice: 3 3{ value: { id: 'A-1', total: 120 }, done: false } A-2plain iterator has helpers: undefinediterator helpers: [ 'A-1', 'A-3' ][ 'MUG-01', 'TEE-03' ]Pitfalls:
- Returning the same iterator every time. An object whose
[Symbol.iterator]()returnsthiscan be iterated only once. Create a new iterator per call. - Using
for...ofon a plain object. It throwsTypeError: ... is not iterable. UseObject.entries. - Forgetting clean-up. If an iterator holds a resource (a file handle, a database cursor), implement
return()sobreakand exceptions release it.
Generators
Section titled “Generators”Introduced in ECMAScript 2015. A generator function, written function*, returns a generator object instead of running its body. Each call to next() runs the body until the next yield, which hands out a value and pauses the function with all its local state. Generator objects are both iterators and iterables, so they work directly with for...of and spread, and they are the easiest way to implement [Symbol.iterator].
Because values are produced on demand, generators are lazy: they suit large or infinite sequences, paging, and pipelines that stop early. yield* other delegates to another iterable. Communication works both ways: next(value) resumes the generator and makes the paused yield expression evaluate to value; throw(error) raises an error at the yield; and return(value) finishes it. When a loop exits early, return() is called, so finally blocks inside the generator run, which is how a generator releases resources.
A generator object can be consumed only once. For sequences that arrive asynchronously, such as pages from an API, use async generators (async function*) with for await...of, covered in Async iteration.
function* orderNumbers(prefix, start = 1) { let n = start; while (true) yield `${prefix}-${String(n++).padStart(4, "0")}`; // infinite but lazy}
function* pages(items, pageSize) { try { for (let i = 0; i < items.length; i += pageSize) { yield items.slice(i, i + pageSize); } } finally { console.log(" pages: clean-up ran"); }}
function* allLines(orders) { for (const order of orders) yield* order.lines; // delegate to each array}
const ids = orderNumbers("WEB", 41);console.log(ids.next().value, ids.next().value, ids.next().value);
const skus = ["MUG-01", "TEE-03", "CAP-07", "LAMP-02", "BAG-05"];for (const page of pages(skus, 2)) { console.log("page:", page); if (page.includes("CAP-07")) break; // finally still runs}
const orders = [{ lines: ["MUG-01", "TEE-03"] }, { lines: ["CAP-07"] }];console.log([...allLines(orders)]);
function* runningTotal() { let total = 0; while (true) { const amount = yield total; // receives the value passed to next() total += amount; }}const totals = runningTotal();totals.next(); // start: run to the first yieldconsole.log(totals.next(20).value, totals.next(17).value, totals.return(0));
const once = allLines(orders);console.log([...once].length, [...once].length);Output:
WEB-0041 WEB-0042 WEB-0043page: [ 'MUG-01', 'TEE-03' ]page: [ 'CAP-07', 'LAMP-02' ] pages: clean-up ran[ 'MUG-01', 'TEE-03', 'CAP-07' ]20 37 { value: 0, done: true }3 0Pitfalls:
- Reusing a generator object. The second spread above is empty. Call the generator function again for a new sequence.
- Forgetting the first
next(). The value passed to the firstnext()is ignored, because noyieldis waiting yet. - Spreading an infinite generator.
[...orderNumbers("WEB")]never ends. Usetake(n)or break out of the loop.
Choosing between them
Section titled “Choosing between them”| Need | Use |
|---|---|
| Copy properties into an existing object, running setters | Object.assign |
| New merged object | Object spread |
| Keys that cannot collide with others | Symbol |
| Intercept every read or write | Proxy with Reflect |
| Lookup by ID, SKU or object | Map |
| Unique values and set algebra | Set |
| Per-object cache or marker without leaks | WeakMap or WeakSet |
Make a class work with for...of |
[Symbol.iterator] implemented with a generator |
| A lazy or infinite sequence | Generator, plus iterator helpers |
Interview questions
Section titled “Interview questions”1. What is the difference between Object.assign({}, a) and { ...a }?
For plain data they give the same shallow copy. Object.assign writes with assignment, so it runs setters on the target and can update an existing object; spread always creates a new object and defines properties without calling setters.
2. When do you choose a Map over a plain object?
When keys come from data or are not strings, when entries are added and removed often, when you need size and reliable insertion order, or when keys like constructor must not collide with inherited properties.
3. Why can you not iterate a WeakMap?
Entries can be removed by the garbage collector at any time, so any listing would depend on collection timing. Without iteration or size, code can only reach an entry through a key it already holds, which keeps behavior deterministic.
4. What are the iterator and iterable protocols?
An iterator has next() returning { value, done } and optionally return() for early exit. An iterable has [Symbol.iterator]() returning a new iterator. for...of, spread, destructuring and Array.from all consume iterables.
5. What does yield return inside a generator?
The value passed to the next(value) call that resumes it. The first next() only starts the generator, so its argument is ignored.
6. Senior scenario: a reporting job loads every order for a year into an array, then filters and maps it, and now runs out of memory. How would you restructure it?
Stream instead of materializing: read orders page by page with an async generator (for await...of), process each order as it arrives, and keep only aggregates, for example in a Map keyed by customer. Use lazy iterator helpers or generator pipelines instead of chained array methods that build intermediate arrays, and make sure the generator’s finally closes the database cursor if the job stops early.
Reading path
Section titled “Reading path”- Rest/spread properties: object spread and rest, and how they differ from
Object.assign. - Object.entries, Object.keys, Object.values and Object.hasOwn: inspecting objects.
- Object.getOwnPropertyDescriptors: copies that keep getters and setters.
- Reflect API: the functions every proxy trap should forward to.
- for…of and Array.from: the main consumers of iterables.
- Async iteration: async generators and
for await...of. - WeakRefs and FinalizationRegistry: observing garbage collection.
Related pages
Section titled “Related pages”- Objects, arrays and JSON: objects, arrays and prototypes from the start.
- Core language features: destructuring, classes and the syntax used here.
- Async and modules: promises and
async/await. - Private fields: why proxies and private fields do not mix.