The Benefits of Template Literals

Also simply knowns as backticks!

The Benefits of Template Literals

As promised, as part of my journey through coding, I am going to share some of what I have learned, and today that something is about template literals!

The benefits of using template literals (back-tick - `) for strings rather than traditional JavaScript strings (" " or ' ') in JavaScript are many.

Introduced in ES6, template literals allow you to embed JavaScript expressions directly into a string without having to adjust the strings by adding and removing quotation marks around the expression (Expression Interpolation).

Below you can see two examples of how strings can be written - can you see the syntactical difference?

Prompt code and console.log of input using Template Literals (`)

Prompt code and console.log of input using standard quotation marks See the difference?

Apart from its clear syntactical advantage, template literals can be used to make a single string span more than one line. It's easier to track what you are doing, and code maintenance becomes significantly easier.

And most importantly, you don't need to worry about having to have quotations marks for each line of string.

Attempting to use one set of quotation marks to create multiple spans in a string, is a bad idea (1st image) - that would be considered broken code. Use template literals instead, and that code is perfectly okay (see 2nd image).

Multi-line string using traditional JS strings - JS does not like that

Multi-line strings using template literals (`) which JS is okay with Again, see the difference?

Whoever is familiar with Markup will realise how similar code with template literals is compared to Markup. Oh, and how can I forget! You literally never have to worry about having to use a backslash when using " " or ' '. Look at how beautiful it looks, it brings a tear to the eye.

let quote = 'He said "You can't handle the truth!"`  - no need to use backslash!

In my humble and newbie opinion, the code looks much cleaner (better code structure), no need to use '+' signs everywhere to concatenate strings. I would definitely advocate for coders new on their JavaScript journey to start using template literals/backticks early on to save themselves a headache.

I would like to thank @YannBrds on Twitter for pushing me to post this on my blog.

If you're still reading, thank you so much, I hope to use this blog to post and share useful information I gain! I would love to connect with other developers to see what they're learning and learn from them - please connect with me on the following:

Twitter: @codewithmohamed

Github: github.com/codewithmohamed

LinkedIn: Mohamed Mohamud

Email: