Computed Keys with Template Literals
You'll learn how to build dynamic property names by embedding expressions directly into strings using template literals.
The Core Idea
You already know how to use computed property names with square brackets [] and variables. Now we level up: template literals let you construct more complex property names by interpolating values into strings on the fly.
Instead of concatenating strings or using plain variables, you can use backticks and ${} syntax to embed expressions right inside your property name. This is perfect when you need property keys that follow a pattern or naming convention.
How It Works
const prefix = "user";
const id = 42;
const obj = {
[`${prefix}_${id}`]: "John Doe"
};
console.log(obj.user_42); // "John Doe"
The template literal `${prefix}_${id}` evaluates to "user_42", which becomes the property key. You're essentially doing string interpolation inside the computed property brackets.
More Examples
const category = "book";
const year = 2024;
const inventory = {
[`${category}Count`]: 150,
[`${category}_${year}`]: "Active",
[`total${category.toUpperCase()}s`]: 200
};
console.log(inventory.bookCount); // 150
console.log(inventory.book_2024); // "Active"
console.log(inventory.totalBOOKS); // 200
Notice how you can call methods like .toUpperCase() inside the template literal — it's a full expression.
When This Shines
Use template literals for computed keys when you need to:
- Combine multiple variables into one property name
- Apply transformations (like uppercasing)
- Follow naming conventions dynamically
Key Takeaway: Template literals inside computed property brackets let you build dynamic, expressive property names through string interpolation, making your object construction more flexible and readable.