DEV Community

How to Create Multi-Line String with Template Literals

Samantha Ming on April 29, 2019

With the arrival of Template Literals, it's finally super easy to produce multi-line strings. Previously, we had to use the \n or separate string...
Collapse
 
flrnd profile image
Florian Rand •

Another good addition to template literals is writing more readable code, for example:

const name = 'Peter'
const age = 35

//instead of the classic concatenation
console.log(name + " is only " + age + " old!")

//we can write something like this:
console.log(`${name} is only ${age} old!`)
Collapse
 
qcgm1978 profile image
Youth •

It also works

console.log(`%s is only %d old!`,name,age)
Collapse
 
samanthaming profile image
Samantha Ming •

Totally! String interpolation is probably one of my most used ES6 feature 💯

Collapse
 
flrnd profile image
Florian Rand •

Same here! Btw I forgot to mention great article! (Concentrated writing the example totally forgot about being polite 😁)

Thread Thread
 
samanthaming profile image
Samantha Ming •

You’re welcome! Btw, thanks for jumping back and leaving this kind comment 😊 You’re making this community really nice to a part of 💛

Collapse
 
daviddalbusco profile image
David Dal Busco •

Interesting. Does it work cross OS?

Let's say I implement the "ES6 console.log way - first example here above" on a Unix kernel, if I share the code with someone on a Windows kernel, it will be interpreted with "multi-lines" too (\n vs \r\n)?

Collapse
 
flrnd profile image
Florian Rand •

JavaScript runs in the browser 😅

Collapse
 
daviddalbusco profile image
David Dal Busco •

Hahaha it should yes 😂

Let's say that my question applies in case I would run the code on the API side or as a local script 😉

It's probably good, I just that I faced so often encoding errors in the past that I was curious about it

Thread Thread
 
flrnd profile image
Florian Rand •

Interesting, Im going ti do some tests later at home with a Windows machine

Thread Thread
 
daviddalbusco profile image
David Dal Busco •

Super cool 🚀

Collapse
 
namstel profile image
Namstel •

I love template literals. I remember having to write HTML templates with the '"\n" +'-notation. So messy, so easy to make mistakes. Great article for beginners!

Collapse
 
samanthaming profile image
Samantha Ming •

Same! And you pointed out the biggest benefit, it helps reduce errors. That’s why clean code so important, it makes it easier to spot errors. And template literals definitely accomplishes that! 💯