Loading lesson path
Concept visual
Start from A
â® Previous Next â¯
Template strings allow you to write strings that span multiple lines and include embedded expressions:
const name = "John";
const age = 30;
const message = "Hello, " + name + "!\n" +
"You are " + age + " years old.";const name = "John";
const age = 30;
const message = `Hello, ${name}!
You are ${age} years old.`;
Template strings use backticks (`) instead of quotes and can include:Multiple lines without \n
Expressions inside ${}const html = `<div>
Formula
< h1 > Title </h1 >
< p > Paragraph </p ></div>
`;Formula
The indentation in multi - line strings becomes part of the string.The indentation becomes part of the string:
const x = `Hello, how are you?
I'm fine, thanks!
`;You can include any valid JavaScript expression inside
${}in a template string:
let firstName = "John";
let lastName = "Doe";let text = `Welcome ${firstName}, ${lastName}!`;let price = 10;
let quantity = 5;let total = `Total: ${price * quantity}`;Using the map function inside template strings:
const items = ["apple", "banana", "orange"];
const list = `You have ${items.length} items:
${items.map(item => `- ${item}`).join('\n')}`;Using ternery operator inside template strings:
const isAdmin = true;
const message = `Status: ${isAdmin ? 'Admin' : 'User'}`;You can also use template strings with a function (called a tag) to modify the output.
Tagged templates are an advanced feature. You might not need them in most cases. The function takes the text and the expression(s) as arguments.