JavaScript Object Properties: Reading, Writing, Dynamic Keys and Inheritance
Dot vs bracket notation, dynamic keys and how they become strings, objects as lookup tables, why reads follow the prototype chain while writes don't, shadowing, shared state on prototypes, inherited setters, property access errors and when assignments fail.
kvi5hnuCode Sprout team member6 min readOn this page
The previous article created objects. Now you'll read and change their properties, and learn the one asymmetry that explains most of JavaScript's inheritance behavior: reading a property follows the prototype chain, writing one doesn't.
Dot and bracket notation
There are two ways to access a property (article 29):
- Dot notation,
obj.name: the name is written literally in the code and must be a valid identifier. - Bracket notation,
obj[expression]: the expression is evaluated at run time, and its value is the name.
const prices = { apple: 1.2, "dragon fruit": 4 };
const item = "apple";
console.log(prices.item); // looks for a property literally named "item"
console.log(prices[item]); // looks for the value of the variable: "apple"
console.log(prices["dragon fruit"]); // names with spaces need brackets
undefined
1.2
4
prices.item vs prices[item] is one of the most common beginner bugs: dot notation never uses a variable's value.
To create or change a property, put either form on the left of an assignment. Assigning to a property that doesn't exist creates it:
const cart = {};
cart.total = 0; // creates "total"
cart["coupon code"] = "SPRING"; // creates "coupon code"
cart.total += 25; // changes it
Keys are strings (or symbols)
Property names are always strings or symbols. Any other value inside brackets is converted to a string first:
const box = {};
const label = { toString() { return "custom"; } };
box[label] = 1; // uses label.toString()
box[1.5] = "x"; // "1.5"
box[null] = "n"; // "null"
console.log(Object.keys(box));
const id = Symbol("id");
box[id] = 7; // symbols stay symbols
console.log(box[id], Object.keys(box).length);
[ 'custom', '1.5', 'null' ]
7 3
So obj[1] and obj["1"] are the same property, and every plain object used as a key becomes "[object Object]", which makes all of them collide. When keys aren't strings, use a Map (part 11). Symbol keys (article 19) don't appear in Object.keys, which makes them good for hidden extension data.
Objects as lookup tables
Because bracket notation takes any string computed at run time, objects work as lookup tables whose keys come from data: a user's choice, a field of a record, a language code:
const greetings = { en: "Hello", pt: "Olá", ja: "こんにちは" };
const greet = (lang) => greetings[lang] ?? greetings.en;
console.log(greet("pt"), greet("de"));
const record = { first: "Ada", last: "Lovelace", born: 1815 };
const columns = ["last", "born"];
console.log(columns.map((col) => record[col]).join(", "));
Olá Hello
Lovelace, 1815
This replaces long if/switch chains with a table (article 40). For tables whose keys come from users or external data, remember the inherited-names problem from the previous article: greetings["constructor"] isn't undefined. Guard with Object.hasOwn (next article), use Object.create(null), or use a Map.
Inheritance: reads go up the chain
When you read obj.x, JavaScript checks obj's own properties first. If x isn't there, it checks the prototype, then the prototype's prototype, until it finds x or reaches null, in which case the result is undefined:
const level1 = { a: 1 };
const level2 = Object.create(level1);
level2.b = 2;
const level3 = Object.create(level2);
level3.c = 3;
console.log(level3.a + level3.b + level3.c); // a and b are inherited
console.log(Object.keys(level3)); // only c is its own
console.log(typeof level3.toString); // from Object.prototype
6
[ 'c' ]
function
Writes stay on the object: shadowing
Assignment never changes a prototype. obj.x = value either updates obj's own x or creates an own x on obj, which then hides, or shadows, any inherited x:

const animal = {
legs: 4,
describe() { return `${this.legs} legs`; },
};
const bird = Object.create(animal);
bird.legs = 2; // own property on bird; animal is untouched
console.log(bird.describe(), animal.describe());
2 legs 4 legs
bird.describe is inherited, but inside it this is bird, so it reads bird's own legs. This combination, shared methods on a prototype and per-object data on the object, is exactly how classes work (part 9).
The shared mutable value trap
"Writes don't touch the prototype" applies to assignment to the property itself. Mutating an object stored in an inherited property is a read followed by a method call, so it changes the shared object:
const template = { tags: [] };
const post1 = Object.create(template);
const post2 = Object.create(template);
post1.tags.push("news"); // reads the inherited array, then mutates it
console.log(post2.tags, Object.hasOwn(post1, "tags"));
[ 'news' ] false
Both posts share one array through the prototype. Give each object its own mutable data (post1.tags = [], or create it in a constructor), and keep prototypes for methods and constants.
The exception: inherited setters
If the inherited property is an accessor with a setter (article 53), assignment calls the setter instead of creating an own property. The setter runs with this set to the object you assigned to, so anything it stores still lands on that object, not on the prototype:
const scaled = {
set level(v) { this._level = v * 10; },
};
const gauge = Object.create(scaled);
gauge.level = 2;
console.log(Object.hasOwn(gauge, "_level"), Object.hasOwn(scaled, "_level"), Object.hasOwn(gauge, "level"));
true false false
Property access errors
Reading a property that doesn't exist is not an error; it gives undefined. Reading a property of null or undefined is a TypeError, because they have no properties:
const order = { customer: null };
console.log(order.discount); // missing property: undefined
try {
order.customer.name; // reading from null
} catch (err) {
console.log(err.name);
}
console.log(order.customer?.name, order.shipping?.address?.city);
undefined
TypeError
undefined undefined
Optional chaining ?. (article 29) is the modern guard; older code wrote order.customer && order.customer.name (article 34). Assigning a property on null or undefined throws as well.
When assignments fail
An assignment obj.p = value fails if:
objhas an own read-only propertyp;objinherits a read-only propertyp: you can't shadow it with an own property by plain assignment;pdoesn't exist, there's no inherited setter, andobjis not extensible (it was frozen, sealed orObject.preventExtensionswas called).
In strict mode (all modules and classes; article 45), a failed assignment throws a TypeError. In sloppy mode it fails silently, and the property just keeps its old value:
const config = Object.defineProperty({}, "id", { value: 1, writable: false });
const derived = Object.create(config);
const locked = Object.preventExtensions({ x: 1 });
(function () {
"use strict";
for (const attempt of [() => { config.id = 2; }, () => { derived.id = 2; }, () => { locked.y = 1; }]) {
try {
attempt();
} catch (err) {
console.log(err.name);
}
}
locked.x = 5; // existing writable properties can still change
console.log(config.id, derived.id, locked.x, locked.y);
})();
TypeError
TypeError
TypeError
1 1 5 undefined
Object.defineProperty, freezing and extensibility are covered in part 14.
Common questions
Dot or bracket notation: which should I use?
Use dot notation whenever the name is fixed and a valid identifier: it's shorter and easier to read, and ESLint's dot-notation rule enforces it. Use brackets when the name is in a variable, computed, or not a valid identifier (obj["content-type"]).
Is reading inherited properties slow?
Engines cache property lookups, so following a short prototype chain costs almost nothing. Long chains and objects whose shape keeps changing are what slow things down, and only in hot code.
Why does obj.hasOwnProperty sometimes throw "is not a function"?
Either the object has no prototype (Object.create(null)), or the data contains a key named hasOwnProperty that shadows the method. Use the static Object.hasOwn(obj, key) instead (ES2022), which works for every object.
How do I read a nested property from a path string like "server.port"?
Split it and walk the object: the code below. The ?. stops at the first missing level instead of throwing.
path.split(".").reduce((obj, key) => obj?.[key], config)
Summary
obj.nameuses a fixed name;obj[expr]evaluates the expression and uses its value as the name.- Keys are strings or symbols; other values in brackets are converted to strings.
- Reads check own properties, then walk up the prototype chain; a missing property gives
undefined. - Writes create or update own properties, shadowing inherited ones; prototypes are never changed by assignment, except through an inherited setter, which still runs on the original object.
- Mutating an object stored in an inherited property changes it for everyone who inherits it.
- Reading or writing a property of
nullorundefinedthrows aTypeError; use?.to guard. - Writes to read-only properties or non-extensible objects throw in strict mode and fail silently otherwise.
Practice Questions
What does this print?
const key = "size";
const shirt = { size: "M", key: "?" };
console.log(shirt.key, shirt[key]);
Answer
? M. shirt.key reads the property literally named "key"; shirt[key] uses the variable's value, "size".
What does this print?
const proto = { count: 0 };
const a = Object.create(proto);
a.count++;
console.log(a.count, proto.count);
Answer
1 0. a.count++ reads the inherited 0, then assigns 1, which creates an own count on a. The prototype keeps 0.
What does this print?
const proto = { items: [] };
const a = Object.create(proto);
const b = Object.create(proto);
a.items.push(1);
console.log(b.items.length);
Answer
1. push mutates the single array that lives on the prototype; there's no assignment to a.items, so no own property is created.
What does this print?
const m = {};
m[{ a: 1 }] = "first";
m[{ b: 2 }] = "second";
console.log(Object.keys(m), m["[object Object]"]);
Answer
[ '[object Object]' ] second. Both objects convert to the same string key, so the second assignment overwrites the first.
Previous: JavaScript Objects: Creating Objects with Literals, new and Object.create

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.