Skip to content
jshacks.dev
Fundamentals

Objects in JavaScript Properties Methods and Descriptors

A JavaScript object is a set of keyed properties with a prototype link. See own versus inherited keys, key order, copying, freezing and the __proto__ trap.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, TypeScript and Node.js logos.

Objects are the one data structure JavaScript was built around, and nearly everything else, arrays, functions, dates and class instances, is an object underneath. Most of the confusing behavior you meet with them follows from three facts: keys are strings or symbols, properties can be inherited, and each property carries hidden attributes. This post covers the first two and the common operations, and leaves the attributes to the post on property descriptors. It runs on Node.js 24, and it assumes the value-versus-reference model from the post on primitives versus objects. The inheritance side is in the guide to prototypes and inheritance.

Creating and reading properties

An object literal lists keys and values. You read with a dot or with brackets, and the bracket form takes any expression.

JavaScript
const invoice = {
  id: 1042,
  customer: "Ada",
  "line items": 3,
  total() {
    return this.id * 2;
  },
};

const field = "customer";

console.log(invoice.id);
console.log(invoice["line items"]);
console.log(invoice[field]);
console.log(invoice.total());
console.log(invoice.missing);

invoice.paid = true;
delete invoice.customer;
console.log(invoice);
Text
1042
3
Ada
2084
undefined
{ id: 1042, 'line items': 3, total: [Function: total], paid: true }

Dot access needs a valid identifier, and brackets handle everything else. Reading a missing property gives undefined and does not throw. Assigning creates a property, and delete removes one. The total entry uses method shorthand, which is a function stored under a key.

Keys are strings or symbols

Whatever you put in brackets is converted to a string, unless it is a symbol. Numbers, booleans and even objects become strings.

JavaScript
const bag = {};

bag[1] = "number key";
bag["1"] = "string key";
bag[true] = "boolean";
bag[{ id: 1 }] = "object";

console.log(Object.keys(bag));
console.log(bag[1]);

const id = Symbol("id");
bag[id] = "hidden";

console.log(Object.keys(bag).length);
console.log(bag[id]);
console.log(Object.getOwnPropertySymbols(bag));
Text
[ '1', 'true', '[object Object]' ]
string key
3
hidden
[ Symbol(id) ]

The numeric key 1 and the string key "1" collided, so the second assignment overwrote the first. The object used as a key became the string "[object Object]", which is why objects make poor dictionary keys and Map exists. A symbol key is a separate, unique key that Object.keys() does not list, which makes it a good place for metadata that must not clash with data keys.

The order of keys

The specification fixes the order in which an object lists its own keys: integer-like strings in ascending numeric order, then other strings in the order they were added, then symbols.

JavaScript
const mixed = { b: 1, 2: "two", a: 1, 1: "one", [Symbol("s")]: 0, "-1": "neg" };

console.log(Object.keys(mixed));
console.log(JSON.stringify(mixed));

for (const key in mixed) {
  console.log(key);
}
Text
[ '1', '2', 'b', 'a', '-1' ]
{"1":"one","2":"two","b":1,"a":1,"-1":"neg"}
1
2
b
a
-1

The integer keys came first and were sorted, even though they were written out of order. "-1" is not a valid array index, so it counts as an ordinary string and sorts by insertion. Do not use an object as an ordered collection keyed by numbers, because the numeric keys will reorder themselves. A Map keeps insertion order for every kind of key.

Own and inherited properties

An object has its own properties and, through its prototype, the properties of other objects. Reading looks at the object first and then up the chain.

JavaScript
const settings = { theme: "light" };

console.log("theme" in settings);
console.log("toString" in settings);
console.log(Object.hasOwn(settings, "theme"));
console.log(Object.hasOwn(settings, "toString"));
console.log(typeof settings.toString);

const bare = Object.create(null);
bare.theme = "dark";
console.log("toString" in bare);

const child = Object.create({ inherited: true });
child.own = true;

for (const key in child) {
  console.log(key);
}
console.log(Object.keys(child));
Text
true
true
true
false
function
false
own
inherited
[ 'own' ]

The in operator reports inherited properties as well, so "toString" in settings is true. Object.hasOwn() asks the narrower question. An object created with Object.create(null) has no prototype, so it has no inherited keys, which makes it a safe dictionary. And for...in walks inherited enumerable properties too, while Object.keys() returns own ones only, so prefer Object.keys() or Object.entries() for iteration. Older code uses obj.hasOwnProperty(key), which breaks when the object has a property of that name or no prototype, and Object.hasOwn() replaced it.

Copying and merging

Spread and Object.assign copy own enumerable properties into a new or existing object. Both copy one level deep.

JavaScript
const defaults = { retries: 3, headers: { accept: "json" } };
const overrides = { retries: 5 };

const merged = { ...defaults, ...overrides };
const same = Object.assign({}, defaults, overrides);

merged.headers.accept = "text";

console.log(merged.retries);
console.log(defaults.headers.accept);
console.log(JSON.stringify(merged) === JSON.stringify(same));
Text
5
text
true

The merged object has the override, and editing its nested headers also changed defaults, because the copy is shallow. The post on shallow and deep copies lists the fixes. Later sources win, so put the defaults first.

Locking an object

Three methods restrict changes, each stricter than the last, and none reaches into nested objects.

JavaScript
const open = { a: 1 };
const noNew = Object.preventExtensions({ a: 1 });
const sealed = Object.seal({ a: 1 });
const frozen = Object.freeze({ a: 1, nested: { b: 1 } });

function attempt(label, object) {
  const results = [];
  for (const step of [
    () => (object.added = 1),
    () => (object.a = 2),
    () => delete object.a,
  ]) {
    try {
      step();
      results.push("ok");
    } catch {
      results.push("blocked");
    }
  }
  console.log(label.padEnd(8), results.join(" "));
}

attempt("open", open);
attempt("noNew", noNew);
attempt("sealed", sealed);
attempt("frozen", frozen);

frozen.nested.b = 2;
console.log(frozen.nested.b, Object.isFrozen(frozen), Object.isFrozen(frozen.nested));
Text
open     ok ok ok
noNew    blocked ok ok
sealed   blocked ok blocked
frozen   blocked blocked blocked
2 true false

The three columns are adding a property, changing one and deleting one. preventExtensions blocks only additions, seal blocks additions and deletions, and freeze blocks all three. The nested object stayed editable, because freezing is shallow. A deep freeze needs a recursive helper, and for most code a type-level readonly or as const in TypeScript is cheaper than a runtime freeze.

The __proto__ trap

The key __proto__ is special on ordinary objects: assigning to it changes the prototype. Parsing untrusted JSON and merging it with Object.assign can set a prototype on the target, and that can plant properties that appear on unrelated objects.

JavaScript
const payload = JSON.parse('{"__proto__": {"admin": true}, "name": "x"}');

console.log(Object.keys(payload));

const viaAssign = Object.assign({}, payload);
const viaSpread = { ...payload };

console.log(viaAssign.admin);
console.log(viaSpread.admin);
console.log(Object.hasOwn(viaSpread, "__proto__"));
Text
[ '__proto__', 'name' ]
true
undefined
true

JSON.parse created an ordinary own property named __proto__. Object.assign used assignment, which invoked the setter and replaced the prototype of the new object, so viaAssign.admin is true without ever being set. Spread defines properties directly, so viaSpread got an own __proto__ and no inherited admin. A deep merge helper that recurses through keys has the same flaw one level down and can reach Object.prototype itself, which is the prototype pollution class of vulnerability. Use Object.hasOwn, skip the keys __proto__, constructor and prototype, or build the target with Object.create(null).

A worked example: counting with an object

The everyday use of a plain object is a lookup table or a counter keyed by a string. The one decision that matters is what to do with a key that has not been seen yet, and the answer shows both the own-property check and the dictionary hazard.

JavaScript
const words = ["map", "set", "map", "constructor", "map", "toString"];

const naive = {};
for (const word of words) {
  naive[word] = (naive[word] ?? 0) + 1;
}

const safe = Object.create(null);
for (const word of words) {
  safe[word] = (safe[word] ?? 0) + 1;
}

console.log(naive);
console.log(Object.entries(safe));
Text
{
  map: 3,
  set: 1,
  constructor: 'function Object() { [native code] }1',
  toString: 'function toString() { [native code] }1'
}
[ [ 'map', 3 ], [ 'set', 1 ], [ 'constructor', 1 ], [ 'toString', 1 ] ]

Both loops read a missing key with ?? and treat it as zero, and the output shows the difference. The plain object went wrong for constructor and toString: those names are inherited from Object.prototype, so naive[word] ?? 0 found a function, not undefined, and adding one to it produced a string such as function Object() { [native code] }1. The failure depends on the input, which is how it survives testing. The Object.create(null) version has no inherited names and counts correctly, and a Map avoids the whole problem. We use a Map for counters over arbitrary text, and a plain object only when the keys are a fixed, known set.

Reading and writing nested values safely

Deeply nested objects invite a chain of property reads, and each link can be missing. Optional chaining shortens the read, and the write needs a guard, since assigning into a missing parent throws.

JavaScript
const config = { server: { port: 8080 } };

console.log(config.server?.port);
console.log(config.database?.host);
console.log(config.database?.host ?? "localhost");

try {
  config.database.host = "db";
} catch (error) {
  console.log(error.name + ": " + error.message);
}

config.database ??= {};
config.database.host = "db";
console.log(config);
Text
8080
undefined
localhost
TypeError: Cannot set properties of undefined (setting 'host')
{ server: { port: 8080 }, database: { host: 'db' } }

The read forms return undefined for a missing branch, and ?? supplies a default. The direct write throws, because config.database is undefined. The ??= operator creates the parent only if it is missing, and then the write succeeds. The post on optional chaining and the post on logical assignment cover both operators in detail.

Where plain objects stop being the right tool

If you need keys that are not strings, ordered keys that may be numeric, or frequent additions and deletions, use a Map. If you need uniqueness of values, use a Set. The comparison of Sets and Maps with objects and arrays lays out when each wins. If the shape is fixed and known, a class or a typed record documents it better than a bag of keys.

Do not iterate with for...in unless you want inherited keys, and do not rely on Object.freeze for security, since it can be bypassed through the prototype or a nested reference.

Objects are defined in the specification under object type, and MDN's page on working with objects is a good tour.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.