DEV Community

Sakshi Tambole
Sakshi Tambole

Posted on

Template Literals in JavaScript

Modern JavaScript has introduced several features that improve code readability and developer experience. One such powerful feature is template literals, which provide a cleaner and more expressive way to work with strings.
The primary goal of template literals, introduced in ES6 (2015), was to solve the readability and maintenance issues of traditional string concatenation. They transformed JavaScript strings from simple text containers into a robust engine for dynamic content generation.

Problems with traditional string concatenation

Before template literals, developers used the + operator to combine strings and variables.

const name = "John";
const age = 25;

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

Output: My name is John and I am 25 years old.

Enter fullscreen mode Exit fullscreen mode

Issues:

  1. Hard to read for long or complex strings.
  2. Error-prone with missing spaces or quotes.
  3. Difficult to manage multi-line strings.
  4. Becomes messy when embedding expressions.

What Are Template Literals?

Template literals are a modern way to handle strings in JavaScript, introduced in ES6. They use backticks (`) instead of quotes and allow embedded expressions.

javascript
let message =
My name is ${name} and I am ${age} years old.`;

`

Template literal syntax

Template literals are a modern way to work with strings in JavaScript. They use backticks (`) instead of single (') or double (") quotes and provide powerful features like interpolation and multi-line support.

Basic Syntax:

`String text ${expression} more text`

Enter fullscreen mode Exit fullscreen mode

Example:

let message = `Hello World`;

Enter fullscreen mode Exit fullscreen mode

Embedding variables in strings

Embedding variables in strings means inserting the value of a variable directly inside a string, instead of joining pieces using +.

In modern JavaScript, this is done using template literals (backticks `) and the ${} syntax.

How It Works

When JavaScript sees ${...} inside backticks (`), it:

  1. Evaluates whatever is inside the braces.
  2. Converts it to a string (if needed).
  3. Inserts it into the final string.

Example

const name = "John";

const message = `Hello, ${name}`;
console.log(message);

Output:
Hello, John

Enter fullscreen mode Exit fullscreen mode

Old Way (Concatenation)

const name = "John";

const message = "Hello, " + name;

Harder to read
Gets messy with multiple variables

Enter fullscreen mode Exit fullscreen mode

Modern Way (Template Literals)

const name = "John";
const age = 25;

const message = `My name is ${name} and I am ${age} years old.`;

Enter fullscreen mode Exit fullscreen mode

Multi-line strings

Multi-line strings allow you to write text that spans across multiple lines without using special characters like \n or string concatenation.

This is made easy using template literals (backticks `).

the Old Way

`javascript
const text = "This is line one.\n" +
"This is line two.\n" +
"This is line three.";

`
Issues:

  • Hard to read
  • Requires \n for new lines
  • Uses + for concatenation
  • Easy to make mistakes

Modern Way: Template Literals

With backticks, you can write multi-line strings naturally:

javascript
const text =
This is line one.
This is line two.
This is line three.`;

Output:

This is line one.
This is line two.
This is line three.

`
How It Works

  • JavaScript preserves line breaks inside backticks
  • No need for \n
  • Formatting stays exactly as written

Use cases in modern JavaScript

  1. Dynamic HTML: Generating multi-line HTML structures with embedded data.

`javascript
const user = "Alice";
const age = 25;

const html =
<div class="card">
<h2>${user}</h2>
<p>Age: ${age}</p>
</div>
;

console.log(html);

`

  1. Logging: Creating detailed log messages with timestamps and variable states.

`javascript
const user = "John";
const status = "Success";

const log = [${new Date().toLocaleTimeString()}] User: ${user}, Status: ${status};

console.log(log);

Output:
[10:30:45 AM] User: John, Status: Success

`

  1. SQL Queries: Constructing dynamic database queries based on user input.

`javascript
const username = "john_doe";

const query = SELECT * FROM users WHERE username = '${username}';

console.log(query);

Output:
SELECT * FROM users WHERE username = 'john_doe'

`

  1. Tagged Templates: Advanced string processing where a function (a "tag") parses the template.

javascript
function highlight(strings, value) {
return
${strings[0]}${value}${strings[1]}`;
}

const name = "Alice";

const result = highlightHello ${name};
console.log(result);

Output:

Hello Alice

`

String Interpolation Visualisation

plaintext
Hello ${name}`

Replace ${name} with value

"Hello John"

`
Before vs after template literals

`javascript
Before (Concatenation):

"Hello " + name + ", you have " + count + " messages."

After (Template Literals):

Hello ${name}, you have ${count} messages.

`

Top comments (0)