Hello dear reader, ๐๐ผ
I will try to explain as best as I can what template literals are & how you can use them. I'll begin with an example.
Joining strings together or technically known as String concatenation in JavaScript.
let name = "Arjun";
let age = 21;
let greeting = "Hello, my name is " + name +". I am " + age +
"years old. \n I work as a Software Engineer.";
console.log(greeting);
// **Output**
// Hello, my name is Arjun. I am 21 years old.
// I work as a Software Engineer.
You might have noticed a few flaws if you tried writing this:
- You had to introduce a plus sign โ every time you wanted to join an expression like
name
orage
to the string. - If you were like me ๐, you might have skipped a few closing quotes and had to fix the syntax error ๐ซ you ended up with.
- You can hardly read the text anymore with all the signs and escape characters ๐คฆ๐พ.
Is there a better way to do this? Well, there is.
Template Literals.
Template Literals solves the drawbacks of string concatenation by introducing the concept of multi-line strings & string interpolation. I will discuss them in a moment but first, the syntax.
Template literals are enclosed in backticks (``
).
console.log(`Hello, Arjun`);
// **Output**
// Hello, Arjun
Multi-Line Strings
Earlier, we saw that you had to introduce a new line escape character to begin on a fresh line. With template literals, you don't have to.
let piece_of_text = `Hello, my name is Arjun Singh.
I make beautiful looking websites for the world to enjoy.
Although that is not the only thing that I do.
I love writing, like this blog post you are reading.`
console.log(piece_of_text)
// **Output**
// Hello, my name is Arjun Singh.
// I make beautiful looking websites for the world to enjoy.
// Although that is not the only thing that I do.
// I love writing, like this blog post you are reading.
String Interpolation
In the example, the addition operator was used to join a string with the output of an expression. But with template literals, you can use placeholders of the form ${expression}
to perform substitutions for embedded expressions
let name = "Arjun";
let age = 21;
let greeting = `Hello, my name is ${name} . I am ${age} years old.
I work as a Software Engineer.`;
console.log(greeting);
// **Output**
// Hello, my name is Arjun. I am 21 years old.
// I work as a Software Engineer.
That looks much better and is easy on the eyes.
Extra Tips
You can add conditionals to your expression and make your template dynamic.
function greet(name) {
console.log(`Hello ${name ? name : "Guest"}`);
}
let name = "Arjun";
greet(name)
// **Output**
// Hello, Arjun
name = null;
greet(name)
// **Output**
// Hello, Guest
Remarks
Congrats ๐๐ผ for reading this till the end. I hope I taught you something new today.
If I missed something, don't hesitate to mention it. If I made a mistake, please correct me.
We can stay connected on Twitter or find out what I build on Github.
Have a productive day. Thank you ๐๐ฝ .