JavaScript Template Literals (Template Strings)

๐Ÿ“˜ What are Template Literals?

Template literals (also called template strings) are a modern way to work with strings in JavaScript. They use backticks ` instead of quotes and allow easy variable interpolation and multi-line strings.

โŒ Old Way (String Concatenation)

let name = "Ahmed";
let age = 26;

let message = "My name is " + name + " and I am " + age + " years old.";
console.log(message);
            

โœ… Using Template Literals

With template literals, you can insert variables directly using ${}.

let name = "Ahmed";
let age = 26;

let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
            

๐Ÿงฎ Using Expressions Inside Template Literals

You can also use calculations and expressions inside ${}.

let price = 100;
let tax = 0.14;

let total = `Total price is ${price + (price * tax)}`;
console.log(total);
            

๐Ÿ“„ Multi-line Strings

Template literals allow multi-line strings without special characters.

let text = `Hello Ahmed,
Welcome to JavaScript lessons.
Enjoy learning!`;

console.log(text);
            
โœ… No need for \n when using template literals.

๐Ÿงช Try It Yourself

Click the button to generate a message using template literals: