Skip to content

JavaScript objects, arrays, prototypes and JSON

Almost all application data in JavaScript is made of objects and arrays: an order is an object, its lines are an array of objects, and the API that sends it to a browser speaks JSON. This page covers the four pieces you need to work with that data: objects and their properties, arrays and the methods that transform them, prototypes (the mechanism behind methods and classes), and JSON for turning data into text and back.

The samples follow an invented shop called OrdersPortal. Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The output shown under each sample was produced with Node.js 22.23. This page assumes you know functions and closures.

Topic What you learn
Objects Creating, reading, updating and copying objects; references versus copies.
Arrays Indexes, adding and removing items, and map, filter, find, reduce and sort.
Prototypes The prototype chain, Object.create and how classes use it.
JSON JSON.stringify and JSON.parse, what JSON cannot represent, and revivers.

An object is a collection of properties: keys (strings or symbols) mapped to values. Values can be anything, including other objects and functions; a function stored on an object is a method. You create most objects with an object literal { ... }.

  • Read with dot notation order.id, or bracket notation order["id"] when the key is in a variable or is not a valid identifier.
  • Add or change a property by assigning to it; remove it with delete.
  • Reading a missing property gives undefined, not an error. Check existence with Object.hasOwn(obj, key) (ES2022) or the in operator, which also sees inherited properties.
  • Object.keys, Object.values and Object.entries return arrays you can loop over.

Objects are reference values. Assigning an object to another variable or passing it to a function copies the reference, not the object, so both names point to the same data. To get an independent copy, spread it ({ ...order }, a shallow copy where nested objects are still shared) or use structuredClone(order) for a deep copy of plain data.

const order = {
id: "A-1001",
customer: { name: "Ana Silva", email: "ana@example.test" },
status: "pending",
describe() {
return `${this.id} (${this.status})`;
},
};
const field = "status";
console.log(order.id, order[field], order.missing);
order.status = "paid";
order.note = "Leave at reception";
delete order.note;
console.log(order.describe(), Object.hasOwn(order, "note"), "describe" in order);
console.log(Object.keys(order));
const sameOrder = order; // copies the reference
sameOrder.status = "shipped";
console.log("original changed too:", order.status);
const shallow = { ...order };
shallow.customer.name = "Ana S.";
const deep = structuredClone({ id: order.id, customer: order.customer });
deep.customer.name = "Someone Else";
console.log("after shallow copy edit:", order.customer.name);
console.log("after deep copy edit:", order.customer.name);

Output:

A-1001 pending undefined
A-1001 (paid) false true
[ 'id', 'customer', 'status', 'describe' ]
original changed too: shipped
after shallow copy edit: Ana S.
after deep copy edit: Ana S.

Pitfalls:

  • Expecting assignment to copy. const copy = order shares the object. Spread or structuredClone it.
  • Shallow copies share nested objects. Changing copy.customer.name after { ...order } changes the original’s customer too.
  • structuredClone drops methods. It copies data only and throws a DataCloneError on functions, so clone plain data, not objects with methods.

An array is an ordered list of values with numeric indexes starting at 0. length is one more than the highest index, and at(-1) (ES2022) reads from the end. Arrays are objects, so typeof reports "object"; use Array.isArray() to test for one.

Some methods mutate the array in place: push/pop (end), unshift/shift (start), splice (middle), sort and reverse. Others return a new array and leave the original alone: map (transform each item), filter (keep matching items), slice (copy a range), concat and spread, and the ES2023 copies toSorted, toReversed and with. find returns the first match or undefined, some and every return booleans, includes checks membership, and reduce folds the array into one value.

Prefer the non-mutating methods for data you received from elsewhere, because other code may still hold a reference to the same array. Sorting deserves special care: without a compare function, sort() converts items to strings, so numbers sort as text.

const lines = [
{ sku: "MUG-01", price: 9.5, qty: 2 },
{ sku: "TEE-03", price: 18, qty: 1 },
{ sku: "CAP-07", price: 12, qty: 0 },
];
const active = lines.filter((line) => line.qty > 0);
const totals = active.map((line) => line.price * line.qty);
const grandTotal = totals.reduce((sum, value) => sum + value, 0);
console.log(totals, grandTotal);
console.log(lines.find((line) => line.sku === "TEE-03")?.price);
console.log(lines.some((line) => line.qty === 0), lines.every((line) => line.price > 5));
console.log(lines.map((line) => line.sku).includes("CAP-07"), lines.at(-1).sku);
const byPrice = lines.toSorted((a, b) => b.price - a.price).map((line) => line.sku);
console.log("sorted copy:", byPrice, "| original first:", lines[0].sku);
const quantities = [10, 9, 100, 1];
console.log("default sort:", [...quantities].sort());
console.log("numeric sort:", [...quantities].sort((a, b) => a - b));
const queue = ["A-1001"];
queue.push("A-1002", "A-1003");
const next = queue.shift();
console.log(next, queue, queue.length);

Output:

[ 19, 18 ] 37
18
true true
true CAP-07
sorted copy: [ 'TEE-03', 'CAP-07', 'MUG-01' ] | original first: MUG-01
default sort: [ 1, 10, 100, 9 ]
numeric sort: [ 1, 9, 10, 100 ]
A-1001 [ 'A-1002', 'A-1003' ] 2

Pitfalls:

  • sort() without a compare function. It sorts as strings, so [10, 9, 100, 1] becomes [1, 10, 100, 9].
  • Mutating while iterating. Calling splice inside forEach skips items. Build a new array with filter.
  • map for side effects. If you do not use the returned array, use for...of or forEach; map signals “I am building a new array”.

Every object has a hidden link to another object, its prototype (read it with Object.getPrototypeOf(obj)). When you read a property the object does not have, JavaScript looks on the prototype, then on the prototype’s prototype, and so on until it reaches null. This is the prototype chain, and it is how objects share methods: an array’s map lives once on Array.prototype, not on every array.

You can create an object with a chosen prototype with Object.create(proto). Constructor functions and class syntax (ES2015) automate this: methods declared in a class body are placed on ClassName.prototype, every instance created with new links to it, and extends links one prototype to another. Classes are not a separate inheritance model; they are clearer syntax over prototypes.

Writing a property always creates or changes it on the object itself; it never modifies the prototype. That is how an instance can override a shared method. To tell own properties from inherited ones, use Object.hasOwn.

const orderMethods = {
total() {
return this.lines.reduce((sum, line) => sum + line.price * line.qty, 0);
},
};
const order = Object.create(orderMethods);
order.lines = [{ price: 9.5, qty: 2 }];
console.log(order.total(), Object.hasOwn(order, "total"), Object.getPrototypeOf(order) === orderMethods);
class Order {
constructor(id, lines) {
this.id = id;
this.lines = lines;
}
total() {
return this.lines.reduce((sum, line) => sum + line.price * line.qty, 0);
}
}
class GiftOrder extends Order {
total() {
return super.total() + 3; // gift wrapping fee
}
}
const gift = new GiftOrder("A-1002", [{ price: 18, qty: 1 }]);
console.log(gift.total(), gift instanceof Order);
console.log(Object.getPrototypeOf(gift) === GiftOrder.prototype);
console.log(Object.getPrototypeOf(GiftOrder.prototype) === Order.prototype);
console.log(Object.keys(gift), typeof Order, Object.hasOwn(Order.prototype, "total"));

Output:

19 false true
21 true
true
true
[ 'id', 'lines' ] function true

Pitfalls:

  • Modifying built-in prototypes. Adding methods to Array.prototype can clash with future standard methods and other libraries. Write a helper function instead.
  • Methods created in the constructor. this.total = function () {} makes a new function per instance. Put shared methods on the prototype or in the class body.
  • Using __proto__. It is a legacy accessor. Use Object.getPrototypeOf and Object.create.

JSON (JavaScript Object Notation) is a text format for data, used by almost every web API and many configuration files. It looks like a JavaScript object literal but is stricter: keys must be in double quotes, strings use double quotes, and there are no comments, trailing commas, functions or undefined.

  • JSON.stringify(value, replacer, space) turns a value into JSON text. The optional space argument indents the output, and replacer can be an array of keys to keep or a function that transforms values.
  • JSON.parse(text, reviver) turns JSON text back into values and throws a SyntaxError on invalid input. The optional reviver function can convert values on the way in, for example ISO date strings back into Date objects.

JSON.stringify is lossy for values JSON cannot represent. Properties whose value is undefined, a function or a symbol are left out; in arrays those values become null. NaN and Infinity become null. A Date becomes an ISO string (through its toJSON method) and comes back as a plain string. A BigInt throws a TypeError, and so does a circular reference.

const order = {
id: "A-1001",
placedAt: new Date("2026-11-02T10:30:00Z"),
total: 37,
discount: NaN,
note: undefined,
format() {
return this.id;
},
tags: ["gift", undefined],
};
const json = JSON.stringify(order);
console.log(json);
console.log(JSON.stringify({ id: order.id, total: order.total }, null, 2));
const parsed = JSON.parse(json);
console.log(typeof parsed.placedAt);
const revived = JSON.parse(json, (key, value) => (key === "placedAt" ? new Date(value) : value));
console.log(revived.placedAt instanceof Date, revived.placedAt.getUTCHours());
for (const bad of ["{ id: 'A-1' }", '{"id":"A-1",}']) {
try {
JSON.parse(bad);
} catch (error) {
console.log(error.name, "for", bad);
}
}
try {
JSON.stringify({ id: "A-1", reference: 9007199254740993n });
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

{"id":"A-1001","placedAt":"2026-11-02T10:30:00.000Z","total":37,"discount":null,"tags":["gift",null]}
{
"id": "A-1001",
"total": 37
}
string
true 10
SyntaxError for { id: 'A-1' }
SyntaxError for {"id":"A-1",}
TypeError: Do not know how to serialize a BigInt

Pitfalls:

  • Silent data loss. undefined properties disappear and NaN becomes null. Validate data before sending it.
  • Dates come back as strings. Revive them with a reviver function or convert them where you use them.
  • Using JSON round-trips as a deep clone. JSON.parse(JSON.stringify(x)) loses dates, undefined, Map, Set and more. Use structuredClone.
Need Use
A record with named fields Object literal
An ordered list Array
Lookup by an arbitrary key, frequent adds and deletes Map (see Objects and collections)
A transformed copy of a list map, filter, toSorted
Shared behavior for many objects class (prototypes underneath)
Data for an API or file JSON.stringify / JSON.parse
An independent copy of plain data structuredClone

1. How do you check whether an object has a property? Object.hasOwn(obj, "key") for own properties, or "key" in obj to include inherited ones. Comparing with undefined fails when a property exists with the value undefined.

2. What is the difference between map, filter and forEach? map returns a new array of transformed items, filter returns a new array of the items that pass a test, and forEach returns undefined and is only for side effects.

3. How does prototype-based inheritance work, and how do classes relate to it? Property lookups that miss on an object continue along its prototype chain. A class puts its methods on Class.prototype, instances link to it, and extends links Sub.prototype to Base.prototype. Classes are syntax over the same mechanism.

4. What does JSON.stringify do with undefined, functions, NaN, dates and BigInt? undefined, functions and symbols are omitted from objects and become null in arrays; NaN and Infinity become null; dates become ISO strings; BigInt throws a TypeError.

5. Senior scenario: a cart component updates state with state.lines.push(newLine); setState(state) and the UI does not re-render, while another screen showing the same cart changes unexpectedly. What is going on? The code mutates the shared array and object in place, so the state reference does not change and change detection that compares references sees no update, while every holder of the same reference sees the mutation. Create new objects instead: setState({ ...state, lines: [...state.lines, newLine] }), and treat received data as read-only.