← Technical

TIL: Computed Property Names in JavaScript

Sometimes you want to specify an object literal in JavaScript that uses the value of a variable as a property name. Unfortunately, JavaScript expects property names to be literal strings, literal numbers, or a symbol (I think?), so you’ll get frustrating syntax errors if you try to use variable references.

This won’t work:

const itemId: string = ...;
const dict = {
    itemId: "1" 
}

Instead, you have to use the computed property name syntax, by surrounding the variable reference with square brackets:

const itemId: string = ...;
const dict = {
    [itemId]: "1" 
}

References