Skip to content

Dynamic Object Properties

Square brackets let the name of a property come from a variable or an expression, so the code can choose which property to read or write while it runs. Dot notation cannot do this, because the word after the dot is always taken as the property name itself.

Inside square brackets, JavaScript evaluates the expression and uses the result as the property name:

const temperatures = { london: 14, leeds: 11, bristol: 15 };
const city = 'leeds';
console.log(temperatures[city]);
console.log(temperatures.city);

This prints:

11
undefined

temperatures[city] looks up the property leeds, which is the value of city. temperatures.city looks for a property literally called city, which does not exist.

The same rule makes it possible to write a function that sets any property it is given:

const setPreference = (prefs, name, value) => {
prefs[name] = value;
return prefs;
};
const prefs = {};
setPreference(prefs, 'theme', 'dark');
setPreference(prefs, 'fontSize', 16);
console.log(prefs);

This prints:

{ theme: 'dark', fontSize: 16 }

A common slip is to use dot notation with the parameter’s name, which creates a property called name every time:

const setWrongly = (prefs, name, value) => {
prefs.name = value;
};
const prefs = {};
setWrongly(prefs, 'theme', 'dark');
console.log(prefs);

This prints:

{ name: 'dark' }

An object literal can also take a name from an expression, by putting the expression in square brackets before the colon. These are called computed property names:

const field = 'email';
const version = 2;
const user = {
name: 'Priya',
[field]: 'priya@example.com',
[`address_v${version}`]: '12 Mill Lane',
};
console.log(user);

This prints:

{
name: 'Priya',
email: 'priya@example.com',
address_v2: '12 Mill Lane'
}

name without brackets is a fixed name, while [field] takes its name from the variable. Any expression works inside the brackets, including a template literal.

Dynamic names are what make an object useful as a lookup table. This counts how often each value appears in an array, adding a property the first time a value is seen:

const counts = {};
for (const fruit of ['apple', 'pear', 'apple', 'plum', 'apple']) {
counts[fruit] = (counts[fruit] ?? 0) + 1;
}
console.log(counts);

This prints:

{ apple: 3, pear: 1, plum: 1 }

The nullish coalescing operator ?? supplies 0 when the property does not exist yet. Property names are always strings or symbols, so a number used in brackets is converted to a string. Where the keys are not strings, or where the keys come from users and could clash with built-in names such as constructor, a Map is the safer choice.

Steve Griffith covers this topic in his video Dynamic Object Properties in JavaScript.