Home TutorialsModern ES6 Syntax Template Literals

Template Literals

by TheScriptKiddie

Template Literals

Template literals can be used anywhere strings are used. Instead of double or single quotes, template literals use backticks (`).

The main benefits of template literals are string interpolation and multi-line display.

String Interpolation

String interpolation refers to the process of accessing JavaScript variables or executing expressions and including that expression in a string. When using a template literal, simply surround the variable or expression with the interpolation operator, ${ }, to signal you would like the value “printed out” into the string. Consider the following example:

let name = 'John';

// Without template literals, tedious/error-prone:
console.log('Hello ' + name + '!');

// Wrong: The sum of 2 and 4 is 24.
console.log('The sum of 2 and 4 is ' + 2 + 4 + '.');

// Correct: The sum of 2 and 4 is 6.
console.log('The sum of 2 and 4 is ' + (2 + 4) + '.');

// With template literals:
console.log(`Hello ${name}!`);
console.log(`The sum of 2 and 4 is ${2 + 4}.`);

Multi-Line Display

You can also use enter/return when typing a template literal. This will cause the string to be displayed on multiple lines. In addition, the newline character (\n) will be added to the string.

let message = `Hello World! This is
a message that takes up
many different lines.`;

You may also like

Leave a Comment