Day 14: Strings and JSON
Lesson 4: Template Literals
You may have noticed that I said there are three ways to make strings and then promptly stopped really talking about one of them, the back tick way ```;
Well making strings with backticks is much newer concept and comes with some extra powers that you will love.
Firstly, they can be multi-line, so this is valid:
1const multiLineString = `so 2this 3is 4fine`;
(Although it won't print out right in a playground so you'll need to take my word for it 😉)
And secondly they make concatenation waaaay easier.
You can place a variable directly into the string if you wrap it in ${}
, like this.
Which, I think, is quite a lot neater than "Welcome to " + name;
In fact, any JavaScript is valid in there, so you can do calculations or call functions.
If you want to add currency in to that you can just put it right in the string, it will look odd if you use $ but it will work: Your Total: ${starter + mains + dessert}
to Your Total: $${starter + mains + dessert}
You can call functions as well
and you can have more than one per template literal.
If you're like me (and most JavaScript developers) then template literals will become your go to for most string creation, if you need to include variables or function calls as part of it.