Skillversitas

Template Literals in JavaScript

Template literals are the modern way to create strings in JavaScript using backticks (`). This feature makes it easy to build dynamic strings with expression interpolation (embedding variables/expressions directly into a string), multi-line strings without escape characters, and tagged templates for more advanced manipulation. Extremely useful for generating HTML, dynamic messages, and campus email templates.


Template Literal Basics

Regular String vs Template Literal

// Regular string — must use concatenation (+)
const name = "John";
const semester = 4;
const message1 = "Hello, " + name + "! You are in semester " + semester;
console.log(message1); // "Hello, John! You are in semester 4"

// Template literal — uses backticks and ${}
const message2 = `Hello, ${name}! You are in semester ${semester}`;
console.log(message2); // "Hello, John! You are in semester 4"

// Expressions inside ${}
const grade = 85;
const status = grade >= 70 ? "Pass" : "Fail";
const message3 = `Grade: ${grade} — Status: ${status}`;
console.log(message3); // "Grade: 85 — Status: Pass"

Code Example: Expression Interpolation

// Regular variable
const student = {
  name: "Amy Lee",
  studentId: "2023001",
  gpa: 3.85,
  active: true
};

// Arithmetic expression
console.log(`GPA × 100 = ${student.gpa * 100}`); // "GPA × 100 = 385"

// Ternary expression
console.log(`Status: ${student.active ? "Active" : "Leave"}`);

// Function call inside a template
function getClassification(gpa) {
  if (gpa >= 3.5) return "Cum Laude";
  if (gpa >= 3.0) return "Very Satisfactory";
  if (gpa >= 2.5) return "Memuaskan";
  return "Cukup";
}

console.log(`Classification: ${getClassification(student.gpa)}`);
// "Classification: Very Satisfactory"

// Nested expression
const creditsList = [3, 4, 3, 2];
const totalCredits = creditsList.reduce((a, b) => a + b, 0);
console.log(`Total credits: ${totalCredits} (${creditsList.length} courses)`);
// "Total credits: 12 (4 courses)"

Multi-line Strings

// Regular string — must use \n
const letter1 = "Dear\n" +
  "Sir/Madam\n" +
  "Here\n\n" +
  "This is to inform you that...";

// Template literal — multi-line right away
const letter2 = `Dear
Sir/Madam
Here

This is to inform you that...`;

// Still a single expression (very clean for HTML)
const htmlTemplate = `
  <div class="card">
    <h2>${student.name}</h2>
    <p>StudentID: ${student.studentId}</p>
    <p>GPA: ${student.gpa}</p>
  </div>
`;

Tagged Templates

Tagged templates let you process a template literal through a special function — very useful for sanitizing input, translation, or dynamic styling.

// The tag function receives an array of strings and the interpolations
function highlight(strings, ...values) {
  let result = "";
  strings.forEach((str, i) => {
    result += str;
    if (i < values.length) {
      result += `<mark>${values[i]}</mark>`;
    }
  });
  return result;
}

const name = "John";
const score = 95;

const output = highlight`Student ${name} mendapat score ${score}`;
console.log(output);
// "Student <mark>John</mark> mendapat score <mark>95</mark>"

// Example: sanitize input for SQL injection prevention
function safe(strings, ...values) {
  let result = "";
  strings.forEach((str, i) => {
    result += str;
    if (i < values.length) {
      // Escape dangerous characters
      const escaped = String(values[i]).replace(/'/g, "''");
      result += `'${escaped}'`;
    }
  });
  return result;
}

const inputUser = "'; DROP TABLE student;--";
const query = safe`SELECT * FROM student WHERE name = ${inputUser}`;
console.log(query);
// SELECT * FROM student WHERE name = ''' DROP TABLE student;--'''

Code Explanation

Feature Syntax Example
Interpolation ${expression} `Hello ${name}`
Multi-line Literal line breaks `line1\nline2` (without \n)
Tagged tag`template` highlight`text ${val}`
Expressions Arithmetic, ternary, functions `${a + b}`

The **backtick ()** is not a single quote ('`). On keyboards it is usually to the left of the digit 1.


Everyday Case Studies

1. Generating Student ID Cards (Dynamic HTML)

const students = [
  {
    name: "John Smith",
    studentId: "2023001",
    majorCode: "Computer Science",
    semester: 4,
    gpa: 3.75,
    photo: "john.jpg"
  },
  {
    name: "Amy Lee",
    studentId: "2023002",
    majorCode: "Information Systems",
    semester: 4,
    gpa: 3.90,
    photo: "amy.jpg"
  },
  {
    name: "Mike Johnson",
    studentId: "2023003",
    majorCode: "Computer Engineering",
    semester: 2,
    gpa: 3.20,
    photo: "mike.jpg"
  }
];

function getGpaColor(gpa) {
  if (gpa >= 3.5) return "#27ae60"; // green — cum laude
  if (gpa >= 3.0) return "#2980b9"; // blue — excellent
  if (gpa >= 2.5) return "#f39c12"; // yellow — satisfactory
  return "#e74c3c";                  // red — below standard
}

function generateStudentCard(student) {
  const gpaColor = getGpaColor(student.gpa);

  return `
    <div class="student-card">
      <img src="${student.photo}" alt="Photo ${student.name}" />
      <div class="info">
        <h3>${student.name}</h3>
        <p class="studentId">StudentID: ${student.studentId}</p>
        <p class="majorCode">${student.majorCode}</p>
        <p class="semester">Semester ${student.semester}</p>
        <p class="gpa" style="color: ${gpaColor}">
          GPA: ${student.gpa.toFixed(2)}
        </p>
      </div>
    </div>
  `;
}

// Generate all the cards
const htmlCard = students
  .map(student => generateStudentCard(student))
  .join("\n");

console.log(htmlCard);

2. Generating Notification Emails

function generateAnnouncementEmail(course, lecturer, date) {
  const formattedDate = new Date(date).toLocaleDateString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric"
  });

  return `
Dear Student ${course},

Lecturer: ${lecturer}
Date: ${formattedDate}

This is to inform you that the final exam
will be held on the date mentioned above.

Please prepare yourself well.

Thank you.
Sincerely,
Committee Academic
  `.trim();
}

const email = generateAnnouncementEmail(
  "Web Programming",
  "Dr. Aaron Watts, M.Cs.",
  "2025-01-15"
);
console.log(email);

3. Log Formatter for Debugging

function log(level, module, message) {
  const timestamp = new Date().toISOString();
  const prefix = {
    INFO: "ℹ️",
    WARN: "⚠️",
    ERROR: "❌",
    DEBUG: "🔍"
  }[level] || "📝";

  return `${prefix} [${timestamp}] [${module}] ${level}: ${message}`;
}

console.log(log("INFO", "Auth", "User login successful"));
console.log(log("ERROR", "Database", "Connection timeout"));
console.log(log("WARN", "API", "Rate limit approaching threshold"));

Conclusion

  • Template literals (backticks `) replace cumbersome string concatenation with ${expression}.
  • Multi-line strings don't need the \n escape — just press Enter.
  • Expression interpolation: variables, arithmetic, ternary operators, even function calls can be used directly inside ${}.
  • Tagged templates are powerful for sanitization, translation, and advanced string manipulation.
  • Extremely useful for generating dynamic HTML such as student ID cards, automated emails, and log formatting.