AI Computer Institute
Expert-curated CS & AI curriculum aligned to CBSE standards. A bharath.ai initiative. About Us

Template Literals: String Interpolation Made Easy

📚 JavaScript Advanced⏱️ 19 min read🎓 Grade 9
✍️ AI Computer Institute Editorial Team Updated: August 2026 CBSE-aligned · Peer-reviewed · 19 min read
Content curated by subject matter experts with IIT/NIT backgrounds. All chapters are fact-checked against official CBSE/NCERT syllabi.

Open a UPI app, make a payment of ₹1,500 to a shop in Pune, and a confirmation message appears: "Hi Ananya, your payment of ₹1,500 to Pune merchant was successful." That sentence was not typed by a human at PhonePe or Google Pay the moment you paid. It was assembled by code, on the fly, by slotting your name, the amount, and the city into a sentence template. Every app that shows you a personalized message — a bank SMS, an IRCTC ticket, a cricket score update, a marks report — is doing exactly this. The question this chapter answers is: what is the cleanest way to build a sentence like that out of pieces of data?

The Old Way: Building Sentences With Plus Signs

Before we learn the better tool, we need to feel the problem it solves. In JavaScript, strings are joined together using the + operator. Suppose you have three pieces of data — a name, a payment amount, and a city — and you want to combine them into one message.

let name = "Ananya";
let city = "Pune";
let amount = 1500;

let message = "Hi " + name + ", your payment of Rs " + amount + " to " + city + " merchant was successful.";

console.log(message);
// Hi Ananya, your payment of Rs 1500 to Pune merchant was successful.

Trace through this line carefully, because the mechanics matter. JavaScript evaluates the + operators left to right. "Hi " joins with the string stored in name to give "Hi Ananya". That joins with ", your payment of Rs " to give "Hi Ananya, your payment of Rs ". Then it joins with the number 1500 — JavaScript automatically converts the number to the text "1500" before joining — giving "Hi Ananya, your payment of Rs 1500". This continues, piece by piece, until the whole sentence is built.

The output is correct, but look at what it cost to write. Every switch between plain text and a variable name means closing one pair of quotes, typing a +, opening another pair of quotes (or dropping them for a variable), and typing another +. Miscount a quote or a plus sign and you get a syntax error, or worse, a message with a missing space: "Rs "+amount without the trailing space silently produces "Rs1500", which is easy to miss when scanning code. As the number of variables grows, so does the number of places you can make this mistake. This is not a made-up inconvenience — it is exactly the kind of bug that shows up in real school and college projects when students build receipt or report-card generators using concatenation.

The New Way: Backticks and the Dollar-Brace Slot

JavaScript gives you a second kind of string, written with backticks ( ` ) instead of single or double quotes. This is called a template literal. A backtick is the key usually found in the top-left corner of an Indian keyboard, sharing a key with the tilde (~) symbol — it is easy to miss the first time you look for it, so it is worth locating on your own keyboard before you type your first template literal.

Inside a template literal, you can drop a variable — or any expression — directly into the text using a special slot written ${ }. JavaScript evaluates whatever is inside the curly braces and inserts the result right where the slot appears. This is called string interpolation: "interpolate" means to insert something into the middle of an existing sequence, and that is precisely what is happening — a computed value is being inserted into the middle of fixed text.

Here is the exact same message from before, rewritten as a template literal:

let message = `Hi ${name}, your payment of Rs ${amount} to ${city} merchant was successful.`;

console.log(message);
// Hi Ananya, your payment of Rs 1500 to Pune merchant was successful.

Compare this line by line with the concatenation version. There is exactly one pair of backticks around the entire sentence — no closing and reopening of quotes. There is not a single + sign. Every variable sits inside ${ }, in the exact position in the sentence where its value should appear, so the code visually resembles the sentence it produces. This is the core advantage of template literals: what you write looks like what you get.

What JavaScript Actually Does With a Template Literal

It helps to have a precise mental model rather than treating ${ } as magic. When JavaScript reaches a template literal, it processes it in three steps, moving through the string from left to right.

Step 1 — Evaluate: for each ${ } slot, JavaScript computes whatever expression is written inside it, using the current values of any variables involved.

Step 2 — Stringify: if the result of that expression is not already text, JavaScript converts it to text. A number like 1500 becomes the text "1500"; other types follow rules covered later in this chapter.

Step 3 — Splice: the resulting text is inserted into the surrounding string at exactly the position where the ${ } slot was written, and every other character in the template literal — the parts outside any ${ } — is copied through unchanged.

The diagram below traces this pipeline for a template literal with two slots, so you can see evaluation, stringification, and splicing happen as separate stages rather than as one opaque operation.

How a template literal becomes a string `Hi ${name}, you scored ${percentage}%.` 1. Evaluate name -> "Ananya" 1. Evaluate percentage -> 86.4 2. Stringify "Ananya" (already text) 2. Stringify 86.4 -> "86.4" 3. Splice -> "Hi Ananya, you scored 86.4%."

Notice what the diagram makes explicit: the two slots are evaluated and stringified independently of each other, and only in the final step does everything — the fixed text and both converted values — get assembled into one string, in order, left to right.

Any Expression Can Live Inside ${ }

A common early assumption is that ${ } can only hold a plain variable name. It can hold any valid JavaScript expression — arithmetic, function calls, comparisons, even a full ternary operator. Whatever is written inside is evaluated first, and only the final result is inserted.

Consider a marks percentage calculation. Rounding it inside the template literal, rather than as a separate line, keeps the formatting logic next to where it is displayed:

let marksObtained = 432;
let maxMarks = 500;
let percentage = (marksObtained / maxMarks * 100).toFixed(1);

console.log(`You scored ${percentage}%.`);
// You scored 86.4%.

Trace it: 432 / 500 is 0.864. Multiplying by 100 gives 86.4. The .toFixed(1) method rounds that to one decimal place and — this detail matters — returns it as a string, "86.4", not a number. Since it is already text, the stringify step in the pipeline above does nothing extra; the value slots straight in.

Now a genuinely conditional expression — a ternary operator — sitting directly inside the slot, deciding which of two words appears based on a comparison:

let marks = 39;
let result = `You have ${marks >= 40 ? "passed" : "failed"} the exam with ${marks} marks.`;

console.log(result);
// You have failed the exam with 39 marks.

Here the expression inside the first slot is the whole ternary marks >= 40 ? "passed" : "failed". JavaScript evaluates the condition marks >= 40 first: with marks equal to 39, this is false, so the ternary evaluates to the string "failed". That string is what gets spliced into the sentence — the comparison itself never appears in the output, only its consequence does. This is a genuinely different capability from concatenation with +, where you cannot write a comparison operator inline without first storing its result in a variable.

Number formatting for money is a place where this really pays off for Indian data. JavaScript's built-in toLocaleString method, called with the locale code 'en-IN', formats a number using the Indian digit-grouping convention — the last three digits together, then groups of two before that — which is different from the international convention used by toLocaleString('en-US').

let salary = 245000;
console.log(`Your monthly salary is Rs ${salary.toLocaleString('en-IN')}.`);
// Your monthly salary is Rs 2,45,000.

Trace it: 245000 has six digits. The Indian grouping rule places a comma after the last three digits (000) and then in groups of two from there: 2,45,000. Compare this with 'en-US', which would produce 245,000 — the same number, grouped differently. Getting this right matters for any Indian finance, payroll, or e-commerce feature; a template literal lets you call .toLocaleString('en-IN') right inside the slot instead of pre-formatting the number on a separate line.

Multi-Line Strings Without Escape Codes

Regular strings in JavaScript cannot span multiple lines — writing an actual line break inside single or double quotes is a syntax error, which is why you may have seen the escape sequence \n used to force a line break inside a normal string. Template literals remove this restriction entirely: any line break you type inside the backticks becomes part of the string, exactly as typed. This is genuinely useful for anything that looks like a printed slip — a railway ticket, a bill, a report card.

let pnr = "8241057963";
let train = "12951 Mumbai Rajdhani";
let seat = "B4-23";

let ticket = `PNR: ${pnr}
Train: ${train}
Seat: ${seat}
Status: Confirmed`;

console.log(ticket);
// PNR: 8241057963
// Train: 12951 Mumbai Rajdhani
// Seat: B4-23
// Status: Confirmed

Notice there is no \n anywhere in this code. The four lines in the output correspond exactly to the four physical lines typed between the backticks in the source code — the template literal captures the layout of the code itself, whitespace and all.

Nesting Template Literals for Conditional Text

Template literals can be nested — a ${ } slot can itself contain another template literal, backticks and all. This is useful when the value to insert is itself built from a mix of fixed text and data, but only under certain conditions.

let rank = 2;
let message = `Your rank is ${rank <= 3 ? `🏆 ${rank}` : rank}.`;

console.log(message);
// Your rank is 🏆 2.

Trace this carefully, because it is the most layered example in this chapter. The outer template literal has one slot, containing the ternary rank <= 3 ? `🏆 ${rank}` : rank. JavaScript first evaluates the condition rank <= 3: with rank equal to 2, this is true. So the ternary evaluates to its "then" branch, which is itself a template literal: `🏆 ${rank}`. That inner template literal is evaluated independently, following the same three-step pipeline — its single slot holds rank, which evaluates to 2, giving the inner string "🏆 2". That inner result is what the outer ternary produces, and it is what gets spliced into the outer sentence, giving the final string "Your rank is 🏆 2." Had rank been 5, the condition would be false, the "else" branch — the plain number rank — would be used instead, and the output would read "Your rank is 5." with no trophy.

What Happens When You Interpolate Something That Is Not Text

The stringify step in the pipeline is not optional, and its rules are worth knowing precisely, because this is where a second real misconception lives: assuming any value "just becomes readable text" automatically. Numbers, as seen above, convert cleanly. Booleans convert to the words "true" or "false". But arrays and objects follow different, specific rules.

An array converts to a string by joining its elements with commas — no brackets, no spaces:

let fruits = ["mango", "guava", "litchi"];
console.log(`Fruits: ${fruits}`);
// Fruits: mango,guava,litchi

A plain object, however, does not know how to describe its own contents in one line, so JavaScript falls back to a generic label:

let student = { name: "Rahul", grade: 9 };
console.log(`Student: ${student}`);
// Student: [object Object]

This is not a bug and not an error — it is JavaScript honestly telling you it could not produce anything more specific than "this is an object" for a plain object dropped directly into a slot. If you actually want the student's name and grade to appear, you must pull those fields out explicitly, such as `Student: ${student.name}, Grade ${student.grade}`, which would correctly produce "Student: Rahul, Grade 9".

Two Mistakes Almost Every Beginner Makes

Mistake 1 — writing { } without the leading dollar sign. The dollar sign is not decoration; it is what tells JavaScript "this brace pair is a slot, not literal text." Drop it, and the braces are treated as ordinary characters to be printed as-is.

let city = "Chennai";
let msg = `Welcome to {city}!`;

console.log(msg);
// Welcome to {city}!   <-- printed literally, city's value was never used

Because there is no $ before {city}, JavaScript never recognizes it as a slot — it is just four characters, {, c, i, and so on, sitting inside the string like any other letter. The variable city is never read at all, which is exactly why this mistake is dangerous: there is no error message to catch it. The code runs perfectly and produces silently wrong output.

Mistake 2 — writing ${ } syntax inside regular quotes instead of backticks. This is the mirror-image error: the interpolation syntax only has meaning inside backtick strings. Inside single or double quotes, ${ } has no special status at all.

let age = 15;
let msg2 = "You are ${age} years old.";

console.log(msg2);
// You are ${age} years old.

Here the string is delimited with regular double quotes, so JavaScript never activates the interpolation pipeline in the first place — the dollar sign, the braces, and the word age inside them are all just literal characters that happen to be sitting between two quotation marks. Between these two mistakes, the rule to hold onto is: interpolation requires both ingredients together — backticks around the whole string, and a dollar sign immediately before each opening brace. Either one alone does nothing.

Practice: Predict the Output

Work out each answer before checking it — this is the same skill a CBSE trace-the-code question tests.

  1. let a = 7, b = 3; console.log(`${a} times ${b} is ${a * b}`);

    Answer: 7 times 3 is 21. The slot ${a * b} evaluates the multiplication first (7 * 3 = 21), then stringifies and splices the result — the expression itself is never shown, only its value.

  2. let score = 55; console.log(`Result: ${score >= 33 ? "Pass" : "Fail"}`);

    Answer: Result: Pass. 55 >= 33 is true, so the ternary picks the first branch, "Pass".

  3. let items = [10, 20, 30]; console.log(`Total items: ${items.length}`);

    Answer: Total items: 3. items.length is a property access, a valid expression — it evaluates to the number 3, which is then stringified.

  4. let n = 1200000; console.log(`Population: ${n.toLocaleString('en-IN')}`);

    Answer: Population: 12,00,000. Applying Indian grouping to 1200000: last three digits 000, then groups of two moving left — 12,00,000 (twelve lakh).

Summary

A template literal is a string written between backticks instead of quotes, and its defining feature is the ${ } slot: anywhere you write ${expression} inside the backticks, JavaScript evaluates that expression, converts the result to text if it is not text already, and splices it into the surrounding string at that exact position — evaluate, stringify, splice, left to right through the whole literal. Because the slot accepts any expression, not just a bare variable, it can hold arithmetic, method calls like .toFixed() or .toLocaleString('en-IN'), comparisons, and full ternary operators, and template literals can even nest inside one another when the inserted content is itself conditional. Backticks also allow real line breaks typed directly into the string, removing the need for \n in anything that spans multiple lines. Non-text values follow specific stringification rules — numbers and booleans convert cleanly, arrays join with commas, and plain objects collapse to the unhelpful label [object Object] unless you extract their fields explicitly. The two errors to watch for are opposite mistakes: braces without a leading $ are printed as literal text, and ${ } syntax written inside ordinary single or double quotes is likewise just literal text — interpolation only activates when both the backticks and the dollar sign are present together.

Think About It

Think about this: How would you explain template literals: string interpolation made easy to a friend who has never seen a computer? What real-world analogy would you use? Imagine you had to build a system using these concepts — what would be your first step? Try this: before moving on, write down three things you learned and one question you still have.

← Destructuring: Unpacking Objects and ArraysES6 Classes: Object-Oriented Programming in JavaScript →

Found this useful? Share it!

📱 WhatsApp 🐦 Twitter 💼 LinkedIn