Lesson goal: Combine text and calculated values in readable messages.
A number by itself does not always explain much:
180
Three notebooks cost ₹180.
A template literal is a way to write text using backticks:
console.log(`Welcome to JavaScript!`);
On many keyboards, the backtick key is near the top-left corner.
Insert a value with ${}
const studentName = "Aman";
console.log(`Welcome, ${studentName}!`);
Welcome, Aman!
${} and inserts its value into the text.Build a bill message
const notebookPrice = 60;
const notebookQuantity = 3;
const notebookTotal = notebookPrice * notebookQuantity;
console.log(
`${notebookQuantity} notebooks at ₹${notebookPrice} each cost ₹${notebookTotal}.`
);
3 notebooks at ₹60 each cost ₹180.
const penPrice = 10;
const penQuantity = 2;
console.log(`Total pen cost: ₹${penPrice * penQuantity}`);
Total pen cost: ₹20
penTotal is often easier to read and reuse.Write a message across several lines
const studentName = "Simran";
const courseName = "JavaScript Basics";
const message = `Student: ${studentName}
Course: ${courseName}
Status: Learning`;
console.log(message);
Student: Simran
Course: JavaScript Basics
Status: Learning
const studentName = "Aman";
console.log("Welcome, ${studentName}!");
Welcome, ${studentName}!
Correct:
console.log(`Welcome, ${studentName}!`);
Create a message using these values:
const itemName = "Notebook";
const price = 60;
const quantity = 3;
Notebook: 3 × ₹60 = ₹180
console.log(`${itemName}: ${quantity} × ₹${price} = ₹${price * quantity}`);
Template literals use backticks. The ${} syntax inserts values or calculation results into your message.