Before ES6 (2015), creating dynamic strings or multi-line text in JavaScript required clumsy string concatenation using the plus operator (+) and escape characters (\n). Template Literals (written with backticks ``...``) revolutionized string formatting in JavaScript.
1. What are Template Literals?
Template literals are string literals delimited by backticks (` `) instead of quotes (' or "`).
They provide two monumental superpowers:
1
String Interpolation: Embedding variables and expressions directly inside strings with ${expression}.
2
Native Multi-Line Strings: Preserving newlines and indentation without \n.
2. String Interpolation (${...})
Instead of messy concatenation:
The Old Way (ES5):
1const name ="Sumit";
2const role ="Full-Stack Developer";
3const years =5;
4
5const bio ="My name is "+ name +", I am a "+ role +" with "+ years +" years of experience.";
The Modern Way (Template Literals):
1const name ="Sumit";
2const role ="Full-Stack Developer";
3const years =5;
4
5const bio =`My name is ${name}, I am a ${role} with ${years} years of experience.`;
Any Valid JavaScript Expression Inside ${...}:
You can perform mathematical calculations, function calls, or ternary logic inside ${}: