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

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!

AWS Devops Guy (mbejda.com)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store