const poem = `Roses are red,
Violets are blue.
This is a multiline string,
And it's pretty cool too.`;
console.log(poem);
If you've ever struggled with creating a multiline string in JavaScript, you're not alone. I've spent countless hours debugging code at 2am only to realize the issue was a silly typo in my string. But fear not, friend! With the introduction of template literals in ES6, creating a JavaScript multiline string is easier than ever.
The Old Way: Using Concatenation or Escaping Newlines
Before template literals, we had to use concatenation or escape newlines to create multiline strings. It was a pain, and the code looked ugly. Here's an example:
const poem = 'Roses are red,\n' +
'Violets are blue.\n' +
'This is a multiline string,\n' +
'And it\'s pretty cool too.';
console.log(poem);
Or, if you wanted to escape newlines:
const poem = 'Roses are red,\n\
Violets are blue.\n\
This is a multiline string,\n\
And it\'s pretty cool too.';
console.log(poem);
It works, but it's not exactly readable. And don't even get me started on trying to debug this at 2am...
The New Way: Using Template Literals
Template literals make creating multiline strings a breeze. Just wrap your text in backticks (`) and you're good to go! Here's an example:
const poem = `Roses are red,
Violets are blue.
This is a multiline string,
And it's pretty cool too.`;
console.log(poem);
Much nicer, right? And if you need to insert variables into your string, template literals make that easy too:
const name = 'Alice';
const age = 30;
const greeting = `Hello ${name}, happy ${age}th birthday!`;
console.log(greeting);
Common Gotchas
- Make sure to use backticks (`) instead of single quotes (') or double quotes ("). Template literals only work with backticks!
- If you're using an older browser or Node.js version that doesn't support ES6, you'll need to transpile your code or use the old concatenation/escaping method.
- Watch out for indentation issues. If you indent your template literal code, those spaces will be included in the final string.

Conclusion
Creating a JavaScript multiline string doesn't have to be painful. With template literals, you can write clean, readable code that's easy to maintain. So next time you need to create a multiline string, ditch the concatenation and escaping — and give template literals a try!
Want to convert your existing code to use template literals? Try out CodeConverter.co, the AI-powered code language converter that makes updating your codebase a breeze!