Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Template Literals

Joining text with + works, but with more values, it becomes hard to read, and it's easy to forget a space or a quote:

const firstName = "Anna";
const age = 25;
console.log("My name is " + firstName + " and I am " + age + " years old.");

There is an easier way: a template literal. It's text written between backticks ` instead of quotes. You can insert a value into it with ${...}:

const firstName = "Anna";
const age = 25;
console.log(`My name is ${firstName} and I am ${age} years old.`);

Both examples print:

My name is Anna and I am 25 years old.

JavaScript replaces every ${...} with the value inside it. The spaces are part of the text, so you can see right away where they are. You can even put a calculation inside ${...}:

const price = 120;
console.log(`Two tickets cost ${price * 2} dollars.`);

This prints:

Two tickets cost 240 dollars.

This works only with backticks. In ordinary quotes, ${...} is just text, and it is printed as it is:

const day = "Monday";
console.log("Today is ${day}.");

This prints:

Today is ${day}.

A template literal is a string like any other, so you can also store it in a variable.

Instructions

  1. 1

    Create a constant forecast with a template literal that inserts the values of day and temperature into the text On Monday it will be 25 degrees.

    In the text, replace Monday with ${day} and 25 with ${temperature}.

  2. 2

    Print forecast. The output should be On Monday it will be 25 degrees.

  3. 3

    On the next line, print the forecast for the following day, when it will be 2 degrees warmer. Use a template literal with a calculation inside ${...}, so that the program prints A day later it will be 27 degrees.

Back

12/15

  1. 1. Printing
  2. 2. Arithmetic Operations
  3. 3. Comments
  4. 4. Variables
  5. 5. Changing a Variable's Value
  6. 6. Quiz: The Order of Commands
  7. 7. Constants
  8. 8. Division and Remainder
  9. 9. Joining Text
  10. 10. Text and Numbers
  11. 11. Quiz: Text and Numbers
  12. 12. Template Literals
  13. 13. Quiz: Template Literals
  14. 14. Reading Errors
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.