Objects & collections
Property access with []
Reading and writing an object's property when its name is in a variable: obj[key].
Why it exists
Often you don't know a property's name in advance: the user picked which column to sort a table by; a groupBy function receives the field name as an argument; translations live in an object and the language is chosen on the fly. Dot notation obj.name only works for a name known while writing the code. Square brackets use the value of an expression — so the code can work with any field.
Where it's used
- Sorting or grouping by a chosen field:
item[key]. - Dictionaries and lookups:
translations[lang],prices[productId]. - Counting:
counts[word] = (counts[word] ?? 0) + 1. - Form fields by name:
values[input.name] = input.value.
Syntax
object[key]
object[key] = value;Examples
const user = { name: "Ann", city: "London" };
const field = "city";
user[field]; // → "London"
user.field; // → undefined — looks for a property called "field"
user["age"] = 25;
user.age; // → 25const counts = {};
for (const word of ["cat", "dog", "cat"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
counts; // → { cat: 2, dog: 1 }const greetings = { en: "Hello", es: "Hola" };
const lang = "es";
greetings[lang]; // → "Hola"const obj = {};
obj[1] = "number";
obj["1"]; // → "number" — object keys become stringsResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
obj.name and obj["name"] are the same thing. The difference is that the brackets can hold any expression: a variable, joined strings, a function call. Its value is turned into a string and used as the property name.
If the property doesn't exist, the result is undefined, with no error. Writing obj[key] = value creates the property if it wasn't there, or overwrites the existing one.
Plain object keys are strings: obj[1] and obj["1"] are the same property. So an object can't tell the number 1 from the string "1", while a Set or Map can.
Brackets are also needed for names you can't write with a dot: with a space, a hyphen, or starting with a digit — obj["first-name"].
Traps
How it differs from…
When to pick something else
If you know the property's name in advance, use a dot — user.name reads more easily than user["name"]. And if the keys aren't strings (objects, or numbers that mustn't be confused with strings), use a Map instead of a plain object.