AI News Hub Logo

AI News Hub

Template Literals in JavaScript

DEV Community
Pratham

The small syntax upgrade that makes a massive difference in how you write strings. If you've written even a little bit of JavaScript, you've done string concatenation. You've jammed variables and text together with + signs, fought with quote marks, and probably ended up with something that looked like this: let name = "Pratham"; let age = 22; let city = "Delhi"; let intro = "Hi, my name is " + name + ". I am " + age + " years old and I live in " + city + "."; console.log(intro); It works. But look at it. Really look at it. Count the quotes. Count the + signs. Count the spaces you had to manually add. Now imagine this string is three lines long with six variables. Welcome to concatenation hell. Template literals fix all of this. They were introduced in ES6 (2015), and once I started using them in the ChaiCode Web Dev Cohort 2026, I genuinely couldn't go back. Let me show you why. Before template literals existed, the + operator was the only way to build strings that included variables or expressions. It works, but it comes with some real pain points. let product = "Laptop"; let price = 75000; let discount = 10; let message = "The " + product + " costs ₹" + price + " but you get " + discount + "% off. Final price: ₹" + (price - (price * discount / 100)) + "."; console.log(message); // "The Laptop costs ₹75000 but you get 10% off. Final price: ₹67500." Try reading that concatenation line. Your eyes jump between strings and variables, you lose track of what's text and what's a value, and the inline math expression makes it even worse. It works, but it's not pleasant to write or read. // Trying to include a quote inside a string let sentence = "She said, \"JavaScript is awesome!\""; console.log(sentence); // She said, "JavaScript is awesome!" You have to escape quotes with backslashes. It's ugly. And if you mix single and double quotes: let html = 'Hello, ' + name + '!'; You're constantly juggling which quote type to use on the outside vs the inside. One wrong move and you get a syntax error. // Want to write HTML on multiple lines? Good luck. let card = "\n" + " " + name + "\n" + " Age: " + age + "\n" + ""; You need \n for line breaks and + at the end of every line. It's fragile, hard to edit, and looks nothing like the actual output. Traditional concatenation forces you to think about the syntax (quotes, plus signs, escape characters, line breaks) more than the actual content of your string. Template literals flip that around. Template literals use backticks ` ` instead of single or double quotes, and ${} to embed variables or expressions directly inside the string. let name = "Pratham"; let age = 22; // Old way — concatenation let intro1 = "Hi, I'm " + name + " and I'm " + age + " years old."; // New way — template literal let intro2 = `Hi, I'm ${name} and I'm ${age} years old.`; console.log(intro1); // Hi, I'm Pratham and I'm 22 years old. console.log(intro2); // Hi, I'm Pratham and I'm 22 years old. Same output. But look at the template literal version — it reads like a normal sentence. No +, no quote juggling, no manual spaces. You just write the string as you want it to appear and drop in variables where you need them. The backtick ` is usually on the top-left of your keyboard, below the Esc key and next to the 1 key. It's the same key as the tilde ~. If you've never used it before, now you will — a lot. The ${} syntax inside a template literal is called string interpolation. Whatever you put between the curly braces gets evaluated and inserted into the string. let course = "Web Dev Cohort 2026"; let platform = "ChaiCode"; console.log(`I'm enrolled in ${course} at ${platform}.`); // I'm enrolled in Web Dev Cohort 2026 at ChaiCode. You're not limited to just variable names. You can put any valid JavaScript expression inside ${}: let price = 1200; let quantity = 3; console.log(`Total: ₹${price * quantity}`); // Total: ₹3600 console.log(`Is expensive? ${price > 1000 ? "Yes" : "No"}`); // Is expensive? Yes console.log(`Half of 50 is ${50 / 2}`); // Half of 50 is 25 function greet(name) { return `Hello, ${name}!`; } console.log(`Message: ${greet("Pratham")}`); // Message: Hello, Pratham! Here's what happens under the hood when JavaScript processes a template literal: Template: `Hi, ${name}! You are ${age} years old.` │ │ ▼ ▼ Evaluate: name = "Pratham" age = 22 │ │ ▼ ▼ Result: "Hi, Pratham! You are 22 years old." JavaScript scans the template, finds each ${}, evaluates the expression inside, converts the result to a string, and splices it in. You get one final, clean string. This is one of my favorite things about template literals. With backticks, line breaks in your code become actual line breaks in the output. No \n, no +, no nonsense. let html = "\n" + " Pratham\n" + " Web Developer\n" + ""; console.log(html); let html = ` Pratham Web Developer `; console.log(html); Both produce the exact same output: Pratham Web Developer But the template literal version looks like actual HTML. You can read it, edit it, and understand it at a glance. And notice — no need to escape the double quotes inside the HTML either, because the string is wrapped in backticks, not quotes. This is where template literals really shine — building dynamic, multi-line output: let name = "Pratham"; let role = "Full-Stack Developer"; let skills = ["JavaScript", "React", "Node.js"]; let profile = ` ========================= Developer Profile ========================= Name: ${name} Role: ${role} Skills: ${skills.join(", ")} ========================= `; console.log(profile); Output: ========================= Developer Profile ========================= Name: Pratham Role: Full-Stack Developer Skills: JavaScript, React, Node.js ========================= Try building that with + and \n. It's doable, but it would be three times as long and ten times as ugly. Let's put traditional concatenation and template literals head to head across different scenarios: // ❌ Before (concatenation) let msg1 = "Welcome, " + name + "!"; // ✅ After (template literal) let msg2 = `Welcome, ${name}!`; // ❌ Before let bio1 = "I'm " + name + ", " + age + " years old, from " + city + "."; // ✅ After let bio2 = `I'm ${name}, ${age} years old, from ${city}.`; // ❌ Before let total1 = "Total: ₹" + (price * qty) + " (including " + (price * qty * 0.18) + " GST)"; // ✅ After let total2 = `Total: ₹${price * qty} (including ${price * qty * 0.18} GST)`; // ❌ Before let card1 = "\n " + title + "\n " + desc + "\n"; // ✅ After let card2 = ` ${title} ${desc} `; // ❌ Before let quote1 = "He said, \"JavaScript is the best!\""; // ✅ After let quote2 = `He said, "JavaScript is the best!"`; The pattern is clear: template literals are shorter, cleaner, and easier to read in every case. Template literals aren't just a "nice to have." They're everywhere in modern JavaScript. Here are the most common places you'll use them: let user = { name: "Pratham", notifications: 5 }; let greeting = `Hello, ${user.name}! You have ${user.notifications} new notifications.`; console.log(greeting); // Hello, Pratham! You have 5 new notifications. let products = [ { name: "Laptop", price: 75000 }, { name: "Phone", price: 25000 }, { name: "Headphones", price: 3000 } ]; let html = products.map(p => `${p.name} — ₹${p.price}`).join("\n"); console.log(`\n${html}\n`); // // Laptop — ₹75000 // Phone — ₹25000 // Headphones — ₹3000 // let userId = 42; let endpoint = `https://api.example.com/users/${userId}/posts`; console.log(endpoint); // https://api.example.com/users/42/posts Compare that to: "https://api.example.com/users/" + userId + "/posts". No contest. let x = 10; let y = 20; console.log(`x = ${x}, y = ${y}, sum = ${x + y}`); // x = 10, y = 20, sum = 30 let field = "email"; let minLength = 5; throw new Error(`Validation failed: "${field}" must be at least ${minLength} characters.`); // Error: Validation failed: "email" must be at least 5 characters. let name = "Pratham"; let age = 22; let city = "Delhi"; // Using template literals let intro = `My name is ${name}. I'm ${age} years old and I live in ${city}.`; console.log(intro); // My name is Pratham. I'm 22 years old and I live in Delhi. let price = 499; let quantity = 4; console.log(`Subtotal: ₹${price * quantity}`); // Subtotal: ₹1996 console.log(`GST (18%): ₹${(price * quantity * 0.18).toFixed(2)}`); // GST (18%): ₹359.28 console.log(`Grand Total: ₹${(price * quantity * 1.18).toFixed(2)}`); // Grand Total: ₹2355.28 let student = { name: "Pratham Bhardwaj", course: "Web Dev Cohort 2026", skills: ["JavaScript", "React", "Node.js"], isActive: true }; let profile = ` ┌────────────────────────────────────┐ │ Student Profile │ ├────────────────────────────────────┤ │ Name: ${student.name} │ Course: ${student.course} │ Skills: ${student.skills.join(", ")} │ Active: ${student.isActive ? "Yes ✅" : "No ❌"} └────────────────────────────────────┘ `; console.log(profile); // ❌ Old way — rewrite this using template literals let old = "Dear " + name + ",\nThank you for enrolling in " + student.course + ".\nYour " + student.skills.length + " skills are noted.\nBest regards."; // ✅ Your rewrite let modern = `Dear ${student.name}, Thank you for enrolling in ${student.course}. Your ${student.skills.length} skills are noted. Best regards.`; console.log(modern); Traditional concatenation with + is messy, hard to read, and error-prone — especially with multiple variables, expressions, or multi-line strings. Template literals use backticks ` and ${} for interpolation. They produce the exact same result but with dramatically better readability. Any JavaScript expression works inside ${} — variables, math, ternaries, function calls, property access — all of it. Multi-line strings just work with template literals. Line breaks in your code become line breaks in the output. No \n needed. Template literals are the standard in modern JavaScript. You'll see them in dynamic HTML, API URLs, error messages, console logs, and everywhere else strings are built dynamically. Template literals are one of those features where you wonder, "How did anyone write JavaScript before this?" The answer is: painfully, with lots of + signs and escaped quotes. ES6 gave us a better way, and there's no reason not to use it. If you take away just one habit from this article, let it be this: every time you reach for + to build a string with variables, stop — and use a template literal instead. Your code will be cleaner, your debugging will be faster, and anyone reading your code will thank you. I'm building these habits through the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and writing about it helps me internalize these patterns. If you're on a similar learning path, I hope this helped. Connect with me on LinkedIn or check out PrathamDEV.in. More articles coming as the journey continues. Happy coding! 🚀 Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode