Template Literals
Building complex text output by constantly concatenating strings and variables with the + operator can become messy. JavaScript provides template literals—a cleaner, more powerful way to interpolate dynamic values into strings.
Syntax
Template literals must be enclosed by backticks (`) instead of standard quotes. To insert a variable directly into the string, place it inside a dollar-sign and curly-brace enclosure: ${variableName}. The engine automatically converts the enclosed value to a string.
const shadeOfRed = 101;
console.log(`The shade is ${shadeOfRed}`);
// Output: The shade is 101
Advanced Logic Interpolation
The ${} syntax is not restricted to variable names; it evaluates valid JavaScript expressions. You can perform mathematics, invoke functions, or run logical checks right inside the template literal.
const price = 2.5;
const quantity = 3;
const item = "coffee";
// Performing math inside the string
console.log(`Total: $${price * quantity}`);
// Output: Total: $7.5
// Calling a string method inside the string
console.log(`I need ${item.toUpperCase()}`);
// Output: I need COFFEE
Practical Example
Generating customized notifications for users requires blending static text with dynamic analytics data. Template literals make constructing these dynamic messages clean and readable.
const name = "Saul Goodman";
const openRate = 30.5;
// Constructing a personalized alert using template literals
const msg = `Hi ${name}, your open rate is ${openRate} percent`;
console.log(msg);
// Output: Hi Saul Goodman, your open rate is 30.5 percent