Skip to content

Template Literals ​

JavaScript often needs to combine strings with variables to create messages. Template literals make this easier by allowing us to insert values directly into strings.

String Concatenation ​

A traditional way to combine strings and variables is with the + operator:

js
const name = "Sam";
const age = 20;
const msg = "Hello " + name + ", you are " + age + " years old.";

This approach becomes difficult to read with more complex strings. You need to carefully match quotes, add spaces, and track multiple + operators. It's also easy to make mistakes with spacing or forget a concatenation operator.

Template Syntax ​

Template literals use backticks and ${ } to insert values into strings:

js
const name = "Sam";
const age = 20;
const msg = `Hello ${name}, you are ${age} years old.`;

This syntax is easier to read, less prone to errors from missing operators or quotes, and makes the final string's structure more visible.

Expressions ​

You can include any JavaScript expression inside ${ }:

js
// Function calls
function sayHello() {
    return "Hello";
}
const name = "Sam";
const msg1 = `${sayHello()}, ${name}!`;  // "Hello, Sam!"

// Simple calculations
const count = 5;
const msg2 = `You have ${count * 2} items`;  // "You have 10 items"

// Math functions and rounding
const price = 15.7;
const msg3 = `Price: ${Math.round(price * 100) / 100} units`;  // "Price: 15.70 units"

// Ternary operator for conditions
const age = 20;
const msg4 = `Status: ${age >= 18 ? "Adult" : "Minor"}`;

// Logical operators for defaults
const username = "";
const msg5 = `Welcome, ${username || "Anonymous"}!`;

Note that only expressions work, not statements. This won't work:

js
const age = 20;
const msg = `Status: ${
    if (age >= 18) {        // Error: 'if' statements don't work in ${ }
        "Adult"
    } else {
        "Minor"
    }
}`;

Use a ternary operator instead, as shown in the example above.

Declarative Templates ​

Template literals let us describe how something should look based on its data. This declarative style is common in modern web frameworks:

js
function UserCard(name, role, loginCount) {
    return `
<div class="user-card">
    <h2>${name || "Anonymous"}</h2>
    <p>Role: ${role}</p>
    <p>Logins: ${loginCount} ${loginCount === 1 ? "visit" : "visits"}</p>
</div>
    `;
}

// Create HTML by calling the function with values
const card1 = UserCard("Sam", "admin", 1);
const card2 = UserCard("", "user", 12);

The multi-line support and expression interpolation make it easy to write readable HTML templates.

External Resources