Start learning free

LESSON 61 OF 348 · STRINGS I

String Interpolation in TypeScript: Template Literals

Lesson Read the full explanation

Many times we will dynamically generate some text using variables. We have done this in previous lessons using string concatenation. Let's see one more example:

let name = "Andy";
let pet = "dog";
let breed = "poodle";

let message = "Hey, " + name + "! Nice " + pet + "! Is it a " + breed + "?";

console.log(message); // Output: Hey, Andy! Nice dog! Is it a poodle?

While this approach perfectly works, it's not ideal. You can see that as our text gets more complicated, it's harder for the reader to visualize all the concatenations in their head.

This can be achieved much easier with string interpolation.


String Interpolation:

String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like:

Hello {name}, nice to meet you!

you would like to replace the placeholder for name of person with an actual name. This process is called string interpolation.


Template literals:

The string interpolation in JavaScript is performed by template literals (strings wrapped in backticks ``) and ${expression} as a placeholder:

let name = "Mike";

message = `Hello ${name}, nice to meet you!`;

console.log(message); // Output: Hello Mike, nice to meet you!

With these ${}, we're defining place holders or holes in our string, and when we run our program these holes will be filled with the value of our variables.

So here we have one place holder or one hole in our string and it is for the value of the name variable.

We can have as many place holders as needed:

let name = "Mike";
let pet = "cat";
let breed = "ragdoll";

let message = `Hey, ${name}! Nice ${pet}! Is it a ${breed}?`;

console.log(message); // Output: Hey, Mike! Nice cat! Is it a ragdoll?

Assignment
Follow the Coding Tutorial and let's practice with string interpolation!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · STRINGS I

    String Interpolation in TypeScript, explained

    The problem with long concatenations

    Concatenation builds text from variables, but as the text grows, the quotes and plus signs pile up:

    let who = "Andy";
    let pet = "dog";
    let breed = "poodle";
    let message = "Hey, " + who + "! Nice " + pet + "! Is it a " + breed + "?";
    console.log(message);
    
    Hey, Andy! Nice dog! Is it a poodle?
    

    This works, but it is hard to read, and it is easy to lose a space or a quote. String interpolation solves the problem: you write the text as a template and mark the places where values go.

    Template literals

    A template literal is a string written between backticks instead of quotes. Inside it, ${expression} is a placeholder: TypeScript evaluates the expression and puts the result into the text.

    let who = "Mike";
    let message = `Hello ${who}, nice to meet you!`;
    console.log(message);
    
    Hello Mike, nice to meet you!
    

    A template can hold as many placeholders as you need, and it reads close to the text it produces:

    let who = "Mike";
    let pet = "cat";
    let breed = "ragdoll";
    console.log(`Hey, ${who}! Nice ${pet}! Is it a ${breed}?`);
    
    Hey, Mike! Nice cat! Is it a ragdoll?
    

    What can go inside ${}

    A placeholder holds any expression, not only a variable name. Arithmetic, method calls and other expressions are evaluated first:

    let language: string = "Spanish";
    console.log(`2 + 3 = ${2 + 3}`);
    console.log(`Upper: ${language.toUpperCase()}`);
    
    2 + 3 = 5
    Upper: SPANISH
    

    The value of the expression is converted to text. A number such as 21 becomes 21 without any extra step. Other values convert in the usual way: true becomes true, null becomes null, undefined becomes undefined, and an array such as [1, 2, 3] becomes 1,2,3. A plain object becomes [object Object], which is rarely what you want.

    Only backticks interpolate

    The placeholder syntax works only inside backticks. In a normal single- or double-quoted string, ${myAge} is just text:

    let myAge: number = 21;
    console.log('I am ${myAge} years old');
    console.log(`I am ${myAge} years old`);
    
    I am ${myAge} years old
    I am 21 years old
    

    If you need a literal ${ inside a template, put a backslash before the dollar sign: \${.

    More than a shorter concatenation

    • Multi-line text. A template literal can span several lines, and the line breaks become part of the string.
    • Both quote kinds. Single and double quotes can appear inside a template without escaping.
    console.log(`Line one
    line two`);
    console.log(`It's "both" quotes`);
    
    Line one
    line two
    It's "both" quotes
    

    The result of a template literal has type string, like any other string, so you can store it in a variable, pass it to a function or concatenate it further.

    Interpolation in everyday code

    Placeholders are handy when a message depends on a condition. An expression with the conditional operator can sit directly inside ${}:

    const label = (n: number) => `${n} item${n === 1 ? "" : "s"}`;
    console.log(label(1));
    console.log(label(2));
    
    1 item
    2 items
    

    Compare that with the concatenation version, n + " item" + (n === 1 ? "" : "s"). Both produce the same text, but the template shows the shape of the final string at a glance. The rule of thumb is to use a template whenever a message mixes fixed text with two or more values, and plain + or += for appending one piece to a string you are building.

    The exercise

    The starter code declares two variables:

    let myAge: number = 21;
    let myLanguage: string = "Spanish";
    

    The task is to print I am AGE years old and I speak LANGUAGE. with the two values filled in, using a template literal and console.log. Write the fixed text, and replace AGE and LANGUAGE with ${myAge} and ${myLanguage}. The sentence ends with a period, which sits right after the second placeholder.

    let myAge: number = 21;
    let myLanguage: string = "Spanish";
    console.log(`I am ${myAge} years old and I speak ${myLanguage}.`);
    

    The output is:

    I am 21 years old and I speak Spanish.
    

    Gotchas

    • Wrong quote characters. The backtick is a different key from the apostrophe. With ' or " the placeholders print as they are written.
    • Spaces and punctuation are part of the template. Check the space before years and the period at the end. Everything outside the placeholders appears in the output exactly as typed.
    • Braces matter. $myAge without braces is not a placeholder, and ${myAge without the closing brace is a syntax error.
    • Keep placeholders simple. A long expression inside ${} is harder to read than a variable computed on the line above.

    Key takeaways

    • A template literal uses backticks and ${expression} placeholders.
    • Placeholders accept any expression, and the result is converted to text.
    • Only backtick strings interpolate.
    • Templates can span lines and contain both quote kinds.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free