Computed Object Keys and Function Names In Javascript

Javascript

For years, I wanted the ability to use variables as object keys in Javascript. Thanks to ES2015, we got the ability to have computed object keys from within the object definition itself.

This isn’t a new or cutting-edge addition, we’ve had it in Javascript for a while now and it is well-supported. The reason for talking about them is a lot of developers do not know about these features or simply forget about them.

In ES5, this wasn’t impossible but you had to do something messier looking like this:

var variableValue = 'A VALUE FROM A VARIABLE.';

var myObject = {};

myObject['This is just: ' + variableValue] = 'But do not worry, it is just a test'

When ES2015 hit the scene, the above could be written like this:

const variableValue = 'A VALUE FROM A VARIABLE.';

let myObject = {
    ['This is just: ' + variableValue]: 'But do not worry, it is just a test'
};

But, we can make it a bit cleaner. Using template literal backticks, we can remove the string concatenation and do the following instead:

const variableValue = 'A VALUE FROM A VARIABLE.';

let myObject = {
    [`This is just: ${variableValue}`]: 'But do not worry, it is just a test'
};

I particularly find dynamic object keys useful when working with Aurelia or Vue.js class binding (for dynamic template classes on elements), or when I am working with Firebase and dynamic values.

And one of my favourite features of all is the ability to use this syntax with function shorthand, allowing you to have named functions:

const ADD_USER_FUNCTION = 'addUser';
const REMOVE_USER_FUNCTION = 'removeUser';

let methods = {
    [ADD_USER_FUNCTION]() {

    },

    [REMOVE_USER_FUNCTION]() {

    }
};

This is the kind of syntax that I use when working with state management libraries, as it allows me to name my getters, mutations and actions using constants for consistency.

The State of JS Survey Is A Farce

The State of JS is a survey that has been running for a few years now, which surveys front-end developers and aims to find out what they’re …

TypeScript 5.6 Is a Game-Changer

The TypeScript team has unveiled the beta version of TypeScript 5.6, and it’s brimming with features designed to make our lives easier. Catching …