How do I interpolate a variable as a key in a JavaScript object?

This works in Firefox 39 and Chrome 44. Don’t know about other browsers. Also it doesn’t work in nodejs v0.12.7.

var a = "whatever";
var b = { [a]: 20 };
console.log(b["whatever"]); // shows 20

That is, to interpolate a variable, enclose it in brackets.

I’m not sure if this is a part of any standard. Originally, I saw such syntax here: https://hacks.mozilla.org/2015/07/es6-in-depth-classes/ where the author defined:

[functionThatReturnsPropertyName()] (args) { ... }

I’m also not sure if you should use that syntax. It’s not widely known. Other members on your team might not understand the code.

Leave a Comment