Tracks
/
JavaScript
JavaScript
/
Syllabus
/
Template Strings
Te

Template Strings in JavaScript

5 exercises

About Template Strings

In JavaScript, template strings allows for embedding expressions in strings, also referred to as string interpolation. This functionality extends the functionality of the built-in String global object.

You can create template strings in JavaScript by wrapping text in backticks. They not only allow the text to include new lines and other special characters, but you can also embed variables and other expressions.

const num1 = 1;
const num2 = 2;

`Adding ${num1} and ${num2} gives ${num1 + num2}.`;
// => Adding 1 and 2 gives 3.

In the example above, backticks - (``) - are used to represent a template string. The${...} is the placeholder that is used for substitution. Any non-string types are implicitly converted to strings. This topic is covered in the type conversion concept. All types of expressions can be used with template strings.

const track = 'JavaScript';

`This track on exercism.org is ${track.toUpperCase()}.`;
// => This track on exercism.org is JAVASCRIPT.

When you are needing to have strings formatted on multiple lines:

`This is an example of using template
strings to accomplish multiple
lines`;

With the available substitution capabilities, you can also introduce logic into the process to determine what the output string should be. One way to handle the logic could be using the ternary operator. This gives the same conditional if/else functionality in a slightly different format.

To implement logic into template string syntax:

const grade = 95;

`You have ${grade > 90 ? 'passed' : 'failed'} the exam.`;
// => You have passed the exam.
Edit via GitHub The link opens in a new window or tab

Learn Template Strings