How to create an object property from a variable value in JavaScript?
You can dynamically create an object property in JavaScript by using computed property names with []
. This method allows a variable to configure the property key:
Spontaneous object property creation
When properties are to be added to an object after its creation, bracket notation
is an efficient method. By using a variable for the property key, you can set the object's property on the fly:
This flexibility is extremely useful when you have keys that are dynamic, or keys that are illegal identifiers.
Leverage computed property names
With the introduction of ES6
, the programming scene was revolutionized with the inclusion of computed property names. Now, expressions can be evaluated as property names in an object literal:
This enhances the syntax by making it more concise and expressive, especially when creating an object in just one line.
The battle of the notations: dot vs bracket
In JavaScript, you have two notations to refer to object properties: dot notation and bracket notation.
The good old dot notation is simple to use, but it has some restrictions. It can refer to predefined property names, meaning, you can't use variables or invalid identifiers as property names with it.
On the other hand, with bracket notation
, you can use variables or any damn string as a property name. This flexibility gives bracket notation
the power to win in most situations!
Unconventional twists
For those who seek extraordinary approaches, I present you IIFEs (Immediately Invoked Function Expressions) and the comma-operator.
IIFEs are self-executing anonymous functions that can be used for defining a property whose value derives from a function:
The comma operator may sound unfamiliar, but it's a surprise tool that can help us chain multiple expressions, including property assignments:
The ES6 "magic"
ES6
also added shorthand property names to the syntax. It increases the conciseness and reduces time in typing, especially when the property name is exactly the same as the variable name:
Was this article helpful?