Skip to main content

Template literals

What template strings are

A template string is a string enclosed in backticks (`, not ' and not ").

javascript
const name = 'Alex'; const message = `Hello, ${name}!`; console.log(message); // Hello, Alex!

Inside a template string you can insert variables and expressions using ${ ... }.


1. Main difference - variable substitution

Before ES6:

javascript
const name = 'Alex'; const age = 25; const msg = 'My name is ' + name + ' and I am ' + age + ' years old.'; console.log(msg); // My name is Alex and I am 25 years old.

With ES6 (template strings):

javascript
const msg = `My name is ${name} and I am ${age} years old.`; console.log(msg); // My name is Alex and I am 25 years old.

The code becomes cleaner, shorter, and more readable.


2. You can insert any expressions

javascript
const a = 5; const b = 10; console.log(`a + b = ${a + b}`); // a + b = 15 console.log(`Random number: ${Math.random()}`); console.log(`Uppercase: ${'js'.toUpperCase()}`);

Everything inside ${ ... } is evaluated as a regular JS expression.


3. Multiline strings without \n

Before:

javascript
const text = 'Line 1\n' + 'Line 2\n' + 'Line 3';

Now:

javascript
const text = ` Line 1 Line 2 Line 3 `; console.log(text);

The newline character (\n) is not needed, the format is preserved as is.


4. Interpolation with nested templates

You can combine templates and even use them inside functions:

javascript
const name = 'Alex'; const hobby = 'coding'; const greeting = `Hello, ${name}! Your hobby is ${hobby.toUpperCase()}.`; console.log(greeting); // Hello, Alex! Your hobby is CODING.

5. Tagged templates (advanced use)

Template strings can be "tagged" with functions for custom processing:

javascript
function highlight(strings, ...values) { return strings.reduce( (result, str, i) => result + str + (values[i] ? `**${values[i]}**` : ''), '' ); } const name = 'Alex'; const lang = 'JavaScript'; console.log(highlight`Hello ${name}, you love ${lang}!`); // Hello **Alex**, you love **JavaScript**!

This is used in libraries like styled-components (CSS in React), graphql-tag, and for safe HTML templates.


6. Comparison with regular quotes

Feature'single' / "double"template
Variable substitutionNoVia ${}
Multiline stringsNo (needs \n)Yes, directly
Nested expressionsNoYes (${x + y})
Tagging (functions)NoYes
Quote character insideNeeds escaping (\')Not needed, unless there is a `
ES supportOlder versionsSince ES6 (2015)

Short recap

What it doesExampleResult
Variable substitutionHello, ${name}"Hello, Alex"
Expressions${1 + 2}"3"
Multiline stringsA\nB"A↵B"
Tagged templatestag`text ${x}`Processed as a function

A simple rule

Regular quotes are for simple strings. Backticks are for dynamic and multiline strings.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.