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.
Issues:
- Hard to read for long or complex strings.
- Error-prone with missing spaces or quotes.
- Difficult to manage multi-line strings.
- 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.
javascriptMy name is ${name} and I am ${age} years old.`;
let message =
`
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`
Example:
let message = `Hello World`;
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:
- Evaluates whatever is inside the braces.
- Converts it to a string (if needed).
- Inserts it into the final string.
Example
const name = "John";
const message = `Hello, ${name}`;
console.log(message);
Output:
Hello, John
Old Way (Concatenation)
const name = "John";
const message = "Hello, " + name;
Harder to read
Gets messy with multiple variables
Modern Way (Template Literals)
const name = "John";
const age = 25;
const message = `My name is ${name} and I am ${age} years old.`;
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:
javascriptThis is line one.
const text =
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
- 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);
`
- 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
`
- 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'
`
- Tagged Templates: Advanced string processing where a function (a "tag") parses the template.
javascript${strings[0]}${value}${strings[1]}`;
function highlight(strings, value) {
return
}
const name = "Alice";
const result = highlightHello ${name};
console.log(result);
Output:
Hello Alice
`
String Interpolation Visualisation
plaintextHello ${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)