0
0
Javascriptprogramming~5 mins

Template literals in Javascript

Choose your learning style9 modes available
Introduction

Template literals make it easy to create strings that include variables or expressions without confusing plus signs.

When you want to combine text and variables in a message.
When you need to write multi-line strings without extra symbols.
When you want to insert the result of a calculation inside a string.
When you want to create readable and clean string templates.
When you want to avoid messy string concatenation with + signs.
Syntax
Javascript
const message = `Hello, ${name}!`;

Use backticks (`) to start and end template literals, not single or double quotes.

Place variables or expressions inside ${} to insert their values.

Examples
Insert a variable inside the string to greet someone by name.
Javascript
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting);
Insert a calculation directly inside the string.
Javascript
const a = 5;
const b = 3;
console.log(`Sum is ${a + b}`);
Create a string that spans multiple lines easily.
Javascript
const multiLine = `This is line one.
This is line two.`;
console.log(multiLine);
Sample Program

This program uses template literals to create a receipt message showing the customer name, number of items, and total price formatted with two decimals.

Javascript
const user = 'Bob';
const items = 3;
const price = 9.99;
const total = items * price;

const receipt = `Customer: ${user}
Items bought: ${items}
Total price: $${total.toFixed(2)}`;

console.log(receipt);
OutputSuccess
Important Notes

Template literals keep your code cleaner and easier to read compared to string concatenation.

You can put any JavaScript expression inside ${}, like math or function calls.

Backticks are required; using single or double quotes will not work for template literals.

Summary

Template literals use backticks and ${} to insert variables or expressions inside strings.

They make multi-line strings and string building simpler and clearer.

Use them whenever you want to combine text and values in a readable way.