Initialize and Define an Object with a Variable as a Key in One Line!

Milos Bejda
1 min readNov 5, 2017

ECMAScript 6 brought us some wonderful features and helped alleviate some Javascript pains. One particular pain I wrestled with for a long time deals with the way JavaScript initialized it’s objects.

Before ECMAScript 6, initializing an object with a variable as a key was a 2 step operation. You would first initialize the object, and then you would give it a variable key while assigning it a value.

Here is an example of what l’m talking about:

Initializing JS object with variable as a key in 2 steps.

EWWWWW. Thankfully those nightmarish days are now gone and never coming back. Because of the new ECMAScript 6 features, we can now make this hard to bear 2 step operation just a 1 step.

Initializing JS object with variable as a key in 1 step.

Don’t believe me? Here is a jsFiddle!

--

--

Responses (1)