Multiline Strings
Creating multi-line strings in JavaScript has always been a bit tricky with traditional strings. You would need to use escape characters (`\n`) or concatenate multiple strings. Template literals make this process much simpler by allowing you to write multi-line strings directly.
Example 1: Basic Multi-Line String
Let’s discuss how you can create a multi-line string using template literals:
const poem = `
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!
`;
console.log(poem);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!
In this example, the string spans multiple lines, & the line breaks are preserved exactly as written. This is much cleaner than using `\n` or concatenation.
Example 2: Multi-Line String with Variables
You can also embed variables or expressions in multi-line strings:
const name = "Alice";
const message = `
Hello, ${name}!
Welcome to the world of JavaScript.
Here, you can create amazing things.
`;
console.log(message);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Hello, Alice!
Welcome to the world of JavaScript.
Here, you can create amazing things.
Here, the variable `name` is embedded in the multi-line string, making it dynamic & easy to read.
Comparison with Traditional Strings
Let’s see how you would create a multi-line string using traditional methods:
// Using escape characters
const oldWay = "Roses are red,\nViolets are blue,\nJavaScript is awesome,\nAnd so are you!";
console.log(oldWay);
// Using concatenation
const concatenatedWay = "Roses are red," + "\n" +
"Violets are blue," + "\n" +
"JavaScript is awesome," + "\n" +
"And so are you!";
console.log(concatenatedWay);
While these methods work, they are harder to read & maintain. Template literals provide a cleaner & more intuitive way to handle multi-line strings.
Why This is Useful
Multi-line strings are often used for things like:
- Writing long messages or paragraphs.
- Formatting code templates or HTML snippets.
- Creating readable output for logs or documentation.
With template literals, you can write multi-line strings naturally, without worrying about escape characters or concatenation.
Expressions
You can include JavaScript expressions inside template literals using ${}. These expressions can be variables, mathematical calculations, or even function calls.
Example
const name = "Alice";
const age = 22;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);

You can also try this code with Online Javascript Compiler
Run Code
Output:
My name is Alice and I am 22 years old.
Explanation:
The ${} syntax allows you to embed variables and computations directly within the string.
Tagged Templates
Tagged templates allow you to call a function with a template literal. The function processes the literal and returns the desired output.
Example
function tag(strings, name, age) {
return `${strings[0]}${name}${strings[1]}${age}${strings[2]}`;
}
const name = "Bob";
const age = 25;
const message = tag`My name is ${name} and I am ${age} years old.`;
console.log(message);

You can also try this code with Online Javascript Compiler
Run Code
Output:
My name is Bob and I am 25 years old.
Explanation:
The tag function receives the template literal as separate parts: a strings array and the interpolated values. This allows for custom formatting or processing of the string.
Quotes Inside Strings
One common issue with traditional strings in JavaScript is handling quotes. If your string contains single or double quotes, you need to escape them using a backslash (`\`). Template literals solve this problem elegantly by allowing you to include quotes directly without any extra effort.
Example 1: Using Quotes in Template Literals
Let’s discuss how you can include quotes inside a template literal:
const quote = `He said, "JavaScript is awesome!"`;
console.log(quote);

You can also try this code with Online Javascript Compiler
Run Code
Output:
He said, "JavaScript is awesome!"
In this example, double quotes are included directly inside the string without needing to escape them. This makes the code cleaner & easier to read.
Example 2: Mixing Single & Double Quotes
You can also mix single & double quotes inside a template literal without any issues:
const mixedQuotes = `She said, 'I love coding in JavaScript!' and added, "It's so powerful."`;
console.log(mixedQuotes);

You can also try this code with Online Javascript Compiler
Run Code
Output:
She said, 'I love coding in JavaScript!' and added, "It's so powerful."
Here, both single & double quotes are used inside the same string. With template literals, you don’t need to worry about escaping them or using alternate quotes.
Comparison with Traditional Strings
Let’s compare this with how you would handle quotes in traditional strings:
// Using single quotes
const singleQuoteString = 'He said, "JavaScript is awesome!"';
console.log(singleQuoteString);
// Using double quotes
const doubleQuoteString = "She said, 'I love coding in JavaScript!'";
console.log(doubleQuoteString);

You can also try this code with Online Javascript Compiler
Run Code
Output:
He said, "JavaScript is awesome!"
She said, 'I love coding in JavaScript!'
While this works, it requires you to carefully choose the type of quotes for the string & escape them if necessary. Template literals eliminate this hassle entirely.
Why This Matters
Handling quotes inside strings is a common task in programming. With template literals, you can focus on writing your content without worrying about escaping characters. This makes your code more readable & less error-prone.
Raw String
The String.raw method allows you to get the raw string from a template literal, preserving escape sequences like \n.
Example
const rawString = String.raw`This is a raw string.\nIt does not process escape characters.`;
console.log(rawString);

You can also try this code with Online Javascript Compiler
Run Code
Output:
This is a raw string.\nIt does not process escape characters.
Explanation:
The String.raw method ensures that escape sequences are treated as plain text instead of being processed.
Nested Templates
You can nest one template literal inside another to create complex strings.
Example
const firstName = "Charlie";
const lastName = "Brown";
const fullName = `${firstName} ${lastName}`;
const greeting = `Hello, ${fullName}! Welcome to JavaScript.`;
console.log(greeting);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Hello, Charlie Brown! Welcome to JavaScript.
Explanation:
Here, one template literal (${firstName} ${lastName}) is embedded inside another to create a final message.
Interpolation
Interpolation is one of the most powerful features of template literals. It allows you to embed variables, expressions, or even function calls directly inside a string. This makes your code more dynamic & easier to read.
Example 1: Embedding Variables
Let’s see how you can embed a variable inside a template literal:
const name = "Bob";
const age = 25;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
Output:
My name is Bob and I am 25 years old.
In this example, the variables `name` & `age` are embedded directly into the string using `${}`. This is much cleaner than traditional concatenation.
Example 2: Embedding Expressions
You can also embed expressions inside template literals. This means you can perform calculations or operations directly within the string.
const a = 10;
const b = 20;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // Output: The sum of 10 and 20 is 30.
Here, the expression `${a + b}` is evaluated, & the result is included in the string.
Example 3: Embedding Function Calls
You can even call functions inside template literals. This is useful for dynamic content generation.
function greet(name) {
return `Hello, ${name}!`;
}
const user = "Alice";
const greeting = `${greet(user)} How are you today?`;
console.log(greeting);
Output:
Hello, Alice! How are you today?
In this example, the `greet` function is called inside the template literal, & its result is included in the string.
Comparison with Traditional Concatenation
Let’s compare interpolation with traditional string concatenation:
const name = "Bob";
const age = 25;
// Using concatenation
const oldWay = "My name is " + name + " and I am " + age + " years old.";
console.log(oldWay);
Output:
My name is Bob and I am 25 years old.
While this works, it’s harder to read & maintain, especially with longer strings or multiple variables. Interpolation makes the code more concise & readable.
Why Interpolation is Useful
Interpolation is particularly useful for:
- Creating dynamic messages or templates.
- Building complex strings with variables & expressions.
- Writing cleaner & more maintainable code.
With interpolation, you can focus on the content of your string without worrying about concatenation or escaping characters.
Frequently Asked Questions
What is the main purpose of template literals in JavaScript?
Template literals make string handling easier by allowing multiline strings, variable interpolation, and embedded expressions, all without using complex concatenation techniques.
How do you write a multiline string using template literals?
You can write a multiline string by simply using backticks and placing your text across multiple lines.
What is the difference between regular strings and template literals?
Regular strings use single or double quotes and require concatenation for variables or expressions, while template literals use backticks and ${} for seamless interpolation.
Conclusion
Template literals in JavaScript simplify string handling by enabling features like multiline strings, embedded expressions, and tagged templates. They reduce the complexity of code and enhance readability, making them an essential tool for modern JavaScript development.