Computed Property Names in JavaScript

Level 3151 keystrokes

Uses computed property names with [] to dynamically set object property names.

JavaScript code

// Define a variable to use as property name
1const key = "color";
// Define a variable to use as property value
2const value = "blue";
// Create object with computed property names
3const obj = {
// [key] evaluates to "color", so this creates { color: "blue" }
4 [key]: value,
// The template literal builds the property name "colorCode"
5 [`${key}Code`]: "#0000FF"
6};
// Prints "blue"
7console.log(obj.color);
// Prints "#0000FF"
8console.log(obj.colorCode);

Output

blue
#0000FF
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • "× 6
  • ;× 5
  • .× 4
  • =× 3
  • :× 2
  • (× 2
  • )× 2
  • [× 2
  • ]× 2
  • {× 2

More JavaScript examples at level 3

← JavaScript typing practice