Dynamic configuration keys
A configuration object needs keys based on a variable such as a field name.
JS Puzzles · Const
Computed property names let object literals derive keys from evaluated expressions. Put the expression in square brackets to create a dynamic property name.
In an object initializer, place an expression inside square brackets to compute a property key. JavaScript evaluates that expression and uses its result as the key, enabling names derived from variables, concatenation, or other runtime values.
{ [expression]: value }const field = "size";
const config = {
[field]: 12,
[`mobile${field[0].toUpperCase()}${field.slice(1)}`]: 4,
};
console.log(config.size); // 12
console.log(config.mobileSize); // 4Expressions in square brackets are evaluated to create the object’s property names.
A configuration object needs keys based on a variable such as a field name.
An object needs consistently formatted keys assembled from prefixes, capitalization, or suffixes.
An object literal needs a method whose name is calculated from an expression.
A computed property name is an object-literal key written as [expression]. JavaScript evaluates the expression and uses its result as the property name.
Follow-up: How would you create a key named mobileSize from size? Use a template literal such as [mobile${param.charAt(0).toUpperCase()}${param.slice(1)}].
The expression is placed inside square brackets, for example {[items]: "Hello"}. The resulting value becomes the key, so an array used there is converted to its property-key representation.
Follow-up: What key does {["A", "B"]: 1} create? The array is converted to the string "A,B", so the resulting key is "A,B".
Computed names are useful when an object must derive keys from variables or expressions rather than fixed identifiers. They provide the object-literal equivalent of dynamically selecting a property name.
Follow-up: How can a computed name be used for a method? Write [expression](parameters) {} inside the object initializer.
object initializerproperty accessor bracket notationmethod definitionsgettersetter