Objects
Assign a new property to an existing object instance
const obj = { a: 1, b: 2 };
// Direct assignment
obj.c = obj.c ?? 3; // only sets if not already present
// Or simply
obj.c = 3;
Assign a default property to many existing objects (an array of objects)
const items = [{ a: 1 }, { a: 2, c: 5 }];
const withDefaults = items.map(item => ({
c: 3, // default value
...item, // existing properties override the default
}));
Put the default before the spread so any existing value wins. If you want the new property to always overwrite, put the spread first:
const withDefault = { c: 3, ...obj };
or
const withDefault = { ...obj, c: obj.c ?? 3 };
Bracket notation
Useful when the key is dynamic (a variable) or not a valid identifier.
const obj = { a: 1, b: 2 };
const newKey = 'c';
const value = 3;
obj[newKey] = value; // obj is now { a: 1, b: 2, c: 3 }
Within a condition
if (!(newKey in obj)) {
obj[newKey] = value;
}
Or more concisely:
obj[newKey] ??= value;
That last one (??=, logical nullish assignment) is the modern shorthand. It only assigns if obj[newKey] is null or undefined.