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?
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).
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.
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: m.mohamud1992@gmail.com