惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
Intezer
宝玉的分享
宝玉的分享
V
Visual Studio Blog
The Cloudflare Blog
云风的 BLOG
云风的 BLOG
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News
P
Proofpoint News Feed
阮一峰的网络日志
阮一峰的网络日志
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
博客园 - Franky
J
Java Code Geeks
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
D
Docker
IT之家
IT之家
小众软件
小众软件
M
MIT News - Artificial intelligence
Spread Privacy
Spread Privacy
雷峰网
雷峰网
C
CERT Recently Published Vulnerability Notes
N
News | PayPal Newsroom
量子位
The Last Watchdog
The Last Watchdog
The Register - Security
The Register - Security
PCI Perspectives
PCI Perspectives
罗磊的独立博客
S
Secure Thoughts
WordPress大学
WordPress大学
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
B
Blog
T
Threatpost
The GitHub Blog
The GitHub Blog
博客园 - 叶小钗
U
Unit 42
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Help Net Security
Cloudbric
Cloudbric
G
Google Developers Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
人人都是产品经理
人人都是产品经理
H
Heimdal Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Last Week in AI
Last Week in AI
Jina AI
Jina AI
O
OpenAI News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
美团技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Template Literals in JavaScript
Pratham · 2026-05-10 · via DEV Community

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);

Enter fullscreen mode Exit fullscreen mode

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.


The Problem with Traditional String Concatenation

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.

Pain Point 1: Readability Gets Destroyed

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."

Enter fullscreen mode Exit fullscreen mode

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.

Pain Point 2: Quotes Inside Strings Are a Nightmare

// Trying to include a quote inside a string
let sentence = "She said, \"JavaScript is awesome!\"";
console.log(sentence); // She said, "JavaScript is awesome!"

Enter fullscreen mode Exit fullscreen mode

You have to escape quotes with backslashes. It's ugly. And if you mix single and double quotes:

let html = '<div class="card"><p>Hello, ' + name + '!</p></div>';

Enter fullscreen mode Exit fullscreen mode

You're constantly juggling which quote type to use on the outside vs the inside. One wrong move and you get a syntax error.

Pain Point 3: Multi-Line Strings Are Painful

// Want to write HTML on multiple lines? Good luck.
let card = "<div class=\"card\">\n" +
           "  <h2>" + name + "</h2>\n" +
           "  <p>Age: " + age + "</p>\n" +
           "</div>";

Enter fullscreen mode Exit fullscreen mode

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.

The Root Problem

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 Literal Syntax

Template literals use backticks ` ` instead of single or double quotes, and ${} to embed variables or expressions directly inside the string.

The Basics

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.

Enter fullscreen mode Exit fullscreen mode

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.

Where's the Backtick Key?

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.


Embedding Variables in Strings (String Interpolation)

The ${} syntax inside a template literal is called string interpolation. Whatever you put between the curly braces gets evaluated and inserted into the string.

Variables

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.

Enter fullscreen mode Exit fullscreen mode

Expressions

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

Enter fullscreen mode Exit fullscreen mode

Function Calls

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(`Message: ${greet("Pratham")}`);
// Message: Hello, Pratham!

Enter fullscreen mode Exit fullscreen mode

String Interpolation — Visual

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."

Enter fullscreen mode Exit fullscreen mode

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.


Multi-Line Strings

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.

Old Way

let html = "<div class=\"card\">\n" +
           "  <h2>Pratham</h2>\n" +
           "  <p>Web Developer</p>\n" +
           "</div>";
console.log(html);

Enter fullscreen mode Exit fullscreen mode

Template Literal Way

let html = `<div class="card">
  <h2>Pratham</h2>
  <p>Web Developer</p>
</div>`;
console.log(html);

Enter fullscreen mode Exit fullscreen mode

Both produce the exact same output:

<div class="card">
  <h2>Pratham</h2>
  <p>Web Developer</p>
</div>

Enter fullscreen mode Exit fullscreen mode

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.

Combining Multi-Line + Interpolation

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);

Enter fullscreen mode Exit fullscreen mode

Output:

=========================
  Developer Profile
=========================
  Name:   Pratham
  Role:   Full-Stack Developer
  Skills: JavaScript, React, Node.js
=========================

Enter fullscreen mode Exit fullscreen mode

Try building that with + and \n. It's doable, but it would be three times as long and ten times as ugly.


Before vs After: A Side-by-Side Comparison

Let's put traditional concatenation and template literals head to head across different scenarios:

Simple Variable Insertion

// ❌ Before (concatenation)
let msg1 = "Welcome, " + name + "!";

// ✅ After (template literal)
let msg2 = `Welcome, ${name}!`;

Enter fullscreen mode Exit fullscreen mode

Multiple Variables

// ❌ Before
let bio1 = "I'm " + name + ", " + age + " years old, from " + city + ".";

// ✅ After
let bio2 = `I'm ${name}, ${age} years old, from ${city}.`;

Enter fullscreen mode Exit fullscreen mode

Expressions Inside Strings

// ❌ Before
let total1 = "Total: ₹" + (price * qty) + " (including " + (price * qty * 0.18) + " GST)";

// ✅ After
let total2 = `Total: ₹${price * qty} (including ${price * qty * 0.18} GST)`;

Enter fullscreen mode Exit fullscreen mode

Multi-Line HTML

// ❌ Before
let card1 = "<div>\n  <h1>" + title + "</h1>\n  <p>" + desc + "</p>\n</div>";

// ✅ After
let card2 = `<div>
  <h1>${title}</h1>
  <p>${desc}</p>
</div>`;

Enter fullscreen mode Exit fullscreen mode

Quotes Inside Strings

// ❌ Before
let quote1 = "He said, \"JavaScript is the best!\"";

// ✅ After
let quote2 = `He said, "JavaScript is the best!"`;

Enter fullscreen mode Exit fullscreen mode

The pattern is clear: template literals are shorter, cleaner, and easier to read in every case.


Use Cases in Modern JavaScript

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:

1. Dynamic UI Content

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.

Enter fullscreen mode Exit fullscreen mode

2. Building HTML Dynamically

let products = [
  { name: "Laptop", price: 75000 },
  { name: "Phone", price: 25000 },
  { name: "Headphones", price: 3000 }
];

let html = products.map(p => `<li>${p.name} — ₹${p.price}</li>`).join("\n");
console.log(`<ul>\n${html}\n</ul>`);
// <ul>
// <li>Laptop — ₹75000</li>
// <li>Phone — ₹25000</li>
// <li>Headphones — ₹3000</li>
// </ul>

Enter fullscreen mode Exit fullscreen mode

3. API URLs with Dynamic Parameters

let userId = 42;
let endpoint = `https://api.example.com/users/${userId}/posts`;
console.log(endpoint);
// https://api.example.com/users/42/posts

Enter fullscreen mode Exit fullscreen mode

Compare that to: "https://api.example.com/users/" + userId + "/posts". No contest.

4. Console Logging for Debugging

let x = 10;
let y = 20;

console.log(`x = ${x}, y = ${y}, sum = ${x + y}`);
// x = 10, y = 20, sum = 30

Enter fullscreen mode Exit fullscreen mode

5. Error Messages

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.

Enter fullscreen mode Exit fullscreen mode


Let's Practice: Hands-On Assignment

Part 1: Basic Interpolation

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.

Enter fullscreen mode Exit fullscreen mode

Part 2: Expression Inside Template Literal

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

Enter fullscreen mode Exit fullscreen mode

Part 3: Multi-Line Student Profile

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);

Enter fullscreen mode Exit fullscreen mode

Part 4: Rewrite Concatenation as Template Literals

// ❌ 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);

Enter fullscreen mode Exit fullscreen mode


Key Takeaways

  1. Traditional concatenation with + is messy, hard to read, and error-prone — especially with multiple variables, expressions, or multi-line strings.
  2. Template literals use backticks ` and ${} for interpolation. They produce the exact same result but with dramatically better readability.
  3. Any JavaScript expression works inside ${} — variables, math, ternaries, function calls, property access — all of it.
  4. Multi-line strings just work with template literals. Line breaks in your code become line breaks in the output. No \n needed.
  5. 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.

Wrapping Up

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