Question
I want to convert the following Ruby code, which assigns a multiline string to a variable, into JavaScript:
text = <<"HERE"
This
Is
A
Multiline
String
HERE
How can I create and assign an equivalent multiline string literal in JavaScript?
Short Answer
By the end of this page, you will understand how JavaScript handles multiline strings, the modern way to write them using template literals, and how this differs from older approaches. You will also see practical examples, common mistakes, and how multiline strings are used in real codebases.
Concept
In JavaScript, a multiline string literal is a string value that spans more than one line in your source code while preserving line breaks.
In Ruby, a heredoc like this:
text = <<"HERE"
This
Is
A
Multiline
String
HERE
lets you write a block of text directly. The JavaScript equivalent is usually a template literal, which uses backticks instead of single or double quotes.
const text = `This
Is
A
Multiline
String`;
This matters because real programs often need to store or generate text with line breaks, such as:
- email bodies
- HTML snippets
- SQL queries
- JSON samples
- logs and reports
- user-facing messages
Before template literals were added to JavaScript, multiline strings were awkward to write. Developers had to join many strings together manually or use escape characters. Template literals made this much simpler and easier to read.
Mental Model
Think of a normal string in quotes like writing a sentence on a single strip of paper.
A multiline string is like writing on a full sheet of paper with several lines. JavaScript template literals let you keep those lines exactly as they appear, instead of cutting them into separate pieces and taping them together.
- Single quotes
'...'and double quotes"..."are best for one-line strings. - Backticks
`...`are best when the text naturally spans multiple lines.
Syntax and Examples
Basic syntax
In modern JavaScript, use backticks for multiline strings:
const text = `This
Is
A
Multiline
String`;
This creates one string containing line breaks.
Equivalent to the Ruby example
const text = `This
Is
A
Multiline
String`;
console.log(text);
Output:
This
Is
A
Multiline
String
Writing the lines directly
Because template literals preserve line breaks, you can also write it like this:
const text = `This
Is
A
Multiline
String`;
That means the actual string contains newline characters between each line.
Older approach: string concatenation
Before template literals, developers often wrote:
const text = "This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String";
Step by Step Execution
Consider this example:
const text = `Line one
Line two
Line three`;
console.log(text);
Step 1: JavaScript sees the backticks
The backticks tell JavaScript that this is a template literal.
Step 2: JavaScript reads everything inside as one string
The contents are:
Line one- newline
Line two- newline
Line three
Step 3: The newlines become part of the string value
So text is not three separate strings. It is one string containing newline characters.
Step 4: console.log(text) prints the string
The output appears on multiple lines:
Line one
Line two
Line three
What the stored value conceptually contains
You can think of it like this:
"Line one\nLine two\nLine three"
The template literal is just a cleaner way to write that value.
Real World Use Cases
Multiline strings are common in many kinds of JavaScript programs.
Email and notification messages
const emailBody = `Hello Alex,
Your order has shipped.
Tracking number: 12345
Thanks!`;
HTML templates
const card = `
<div class="card">
<h2>Product</h2>
<p>In stock</p>
</div>`;
SQL queries in server-side JavaScript
const query = `
SELECT id, name
FROM users
WHERE active = true`;
API mock data or sample payloads
const sampleJson = `{
"name": "Alice",
"role": "admin"
}`;
Reports and logs
const report = `Daily Summary
Users: 120
Errors: 2
Status: OK`;
Whenever the text is naturally structured across several lines, a multiline string improves readability.
Real Codebase Usage
In real projects, developers often use multiline strings with a few common patterns.
Templates for readable output
Instead of building strings with many + operators, developers use template literals for cleaner formatting.
function buildMessage(user, status) {
return `User: ${user}
Status: ${status}`;
}
Guard clauses before generating text
A function may validate inputs before returning a multiline message.
function createReceipt(name, total) {
if (!name) return "Invalid customer name";
if (total < 0) return "Invalid total";
return `Receipt
Customer: ${name}
Total: $${total}`;
}
Configuration and test fixtures
Developers often store sample file content, raw HTTP requests, or mock responses as multiline strings in tests.
const mockResponse = ;
Common Mistakes
1. Using single or double quotes for multiple lines directly
This is invalid:
const text = "This
Is
Wrong";
Use backticks instead:
const text = `This
Is
Correct`;
2. Confusing quotes with backticks
These are not the same:
- single quotes:
' - double quotes:
" - backticks:
`
Only backticks create template literals.
3. Adding unwanted indentation
This code preserves spaces at the start of each line:
const text = `
first line
second line
`;
That may produce output with leading spaces. If spacing matters, align the text carefully.
4. Expecting old concatenation rules to behave the same way
This works, but is less readable:
const text = "Line 1\n" +
"Line 2\n" +
;
Comparisons
Multiline string approaches in JavaScript
| Approach | Example | Multiline support | Readability | Notes |
|---|---|---|---|---|
| Single quotes | 'hello' | No | High for short strings | Best for simple one-line strings |
| Double quotes | "hello" | No | High for short strings | Same core behavior as single quotes |
| Concatenation | "a\n" + "b" | Yes | Medium to low | Older style, verbose |
| Template literals | `a\nb` or actual line breaks | Yes |
Cheat Sheet
Quick syntax
const text = `Line 1
Line 2
Line 3`;
One-line equivalent
const text = "Line 1\nLine 2\nLine 3";
With variables
const name = "Mia";
const text = `Hello ${name}
Welcome!`;
Rules
- Use backticks for multiline strings.
- Line breaks inside a template literal are preserved.
${value}inserts variables or expressions.- Spaces and indentation are also preserved.
Avoid
const bad = "Line 1
Line 2";
Prefer
const good = `Line 1
Line 2`;
Good use cases
- formatted messages
- HTML snippets
- SQL queries
FAQ
How do you write a multiline string in JavaScript?
Use a template literal with backticks:
const text = `First line
Second line`;
Can I use single quotes for multiline strings in JavaScript?
Not directly. Single-quoted strings cannot span lines in source code without escaping or concatenation.
What is the modern JavaScript equivalent of a Ruby heredoc?
Usually a template literal. It lets you write text across multiple lines and supports variable interpolation.
Do template literals keep line breaks?
Yes. Any line breaks inside the backticks become part of the string.
Do template literals preserve spaces too?
Yes. Leading spaces and indentation are preserved, so format the text carefully.
Are template literals only for multiline strings?
No. They are also useful for inserting variables with ${...} and building readable strings.
Is \n the same as pressing Enter inside a template literal?
Both create a newline in the string. Template literals are often easier to read because you can write the lines directly.
Mini Project
Description
Build a small JavaScript message generator that creates a formatted multiline receipt. This demonstrates how multiline strings are used in practical programs to generate readable output for logs, emails, summaries, or printable text.
Goal
Create a function that returns a receipt as a multiline string using a template literal.
Requirements
- Create a function that accepts a customer name and total amount.
- Return the receipt as a multiline string.
- Include at least three lines of output.
- Print the result to the console.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.