Template Literals In JavaScript for Dummies
All you Need to know about Template Literals and there use in JavaScript.
In JavaScript there are a few ways you can write strings. These include using “double-quotes”, ‘single-quotes’ and `template-literals
`. You might wonder why? This is because JavaScript is a Loosely Typed Language (More on that Later)
Lets talk about Template Literals.
Template Literals are special strings that use a special syntax. These Strings are denoted by using back-ticks (`). This allows JavaScript to know that this is a special syntax. We can also use back-ticks to write normal strings. But there are a few cheeky things we can do with out special syntax that is using back-ticks:
- Multi Line Strings.
- String Interpolation
- Tagged Template Literals
Multi-Line Strings
When we use back-ticks in normal strings JavaScript Pre-formats this, meaning that we do not need to format strings:
console.log(`This is the first Line
This is the second Line`);
//Output:
//This is the first Line
//This is the second Line
We tell JavaScript by using back-ticks that this is a new syntax, do not treat it like normal strings.
Template literals
In the same way Template Literals also use back-ticks for special execution. To use Template Literals we first use our special syntax i.e. back ticks and further put ${}
symbol to denote that we are using a template literal.
Use of Template Literals is to dynamically add values in the string. An Example would be:
const a = 5;
const b = 10;
console.log(`Addition = ${a+b}
Subtraction = ${b-a}
Multiplication = ${a * b}`);
// output:
// Addition = 15
// Subtraction = 5
// Multiplication = 50
Tagged Template Literals
Tagged template literals is a more advanced form of template literals. Tags allows us to parse template literals with a function. The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. An Example would be:
Dive Deeper into Template Literals in the following MDN Web Docs:
If you have made it this far kudos to you 👏 you learned something new today, let me know by giving it a 💛 This was my first attempt at writing on medium. I will try to post things that I learn in my Development Career. If you have any questions or suggestions about what I should write next, please don’t hesitate to put them into comment section. I really hope you enjoyed and I’ll you see you very very soon. Thanks.