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
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}.
Print forecast. The output should be On Monday it will be 25 degrees.
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.
Start programming for free
10/12