Why you should start using template literals right now!

Sebastiaan Nijland
Kaartje2go
Published in
2 min readSep 3, 2018

Template literals are one of the best things to happen to JavaScript️, ranking only slightly below the invention of the internet itself. Here's why.

Note: this post may or may not be exaggerated.

Old, ugly code…

Old, ugly code — or is it just me thinking that?

There's a lot going on there. We get the user name from somewhere. We, quite literally, add some strings together and store it in a variable. We add two newlines and some more text to that variable — for readability, we do this on a newline, losing immutability along the way.

We need a hero!

Don't worry: template literals are here to save the day! They will clean up our code, make it a lot nicer to read and more concise as well. While we're at it, we might as well bring in the helping hand of const. We won't even lose immutability!

Thank you, template literal!

Look how nice that is! We can use ${userName} to add the value of that (immutable, sort of, anyway!) variable directly in the string. No need to 'add' it (which, really, feels like it should be used for arithmetic only and not string manipulation).

"But, but… you're cheating with those newlines!"

Okay, so let's ditch them. Who can remember that \n adds a newline anyway?

Template literals save the day once more!

Yes, that works! It is pretty amazing, and feels really WYSIWYG to me.

Let's take it one step further

Maybe you want to show a generic message if userName is not defined. There is no need to add another string, the condition can go inside the template literal!

If this does not blow your mind, then you already know template literals.

So, what are you waiting for? Start refactoring that code! Still not convinced? Need some help? Check out the MDN docs or try any of the gazillion medium posts out there.

--

--