Template Literals

  • This lesson explains how template literals simplify string handling.
  • Introduction to Template Literals

    In JavaScript, strings are used to store and manipulate text.
    Traditionally, strings were created using:

    • Single quotes (' ')

    • Double quotes (" ")

    However, these traditional strings have limitations when:

    • Combining strings and variables

    • Writing multi-line strings

    • Creating dynamic messages

    To solve these problems, Template Literals were introduced in ES6 (ES2015).

    What are Template Literals ?

    Template literals are a modern way of creating strings in JavaScript using backticks ( ) instead of single or double quotes.

    They allow:

    • Easy variable insertion

    • Expression evaluation

    • Multi-line strings

    • Cleaner and more readable code

    Syntax of Template Literals

    `string text`

    Key points:

    • Uses backticks ( )

    • Supports embedded expressions

    • Supports multi-line formatting

      Traditional Strings vs Template Literals

    Creating Strings Using Concatenation

    Combines variables and text using the + operator to form a string

    let name = "Rahul";
    let age = 22;
    
    let message = "My name is " + name + " and my age is " + age;
    console.log(message);
    • Problems:

      • Too many + operators

      • Hard to read

      • Not scalable for large strings

    Creating Strings Using Template Literals

    Uses backticks and ${} to embed variables inside a string

    let name = "Rahul";
    let age = 22;
    
    let message = `My name is ${name} and my age is ${age}`;
    console.log(message);
    • Advantages:

      • Clean syntax

      • Easy to understand

      • No string concatenation

      Variable Interpolation in Template Literals

      Template literals use ${ } to insert variables or expressions.

    Insert Variables Inside String Using Template Literals

    Allows embedding variables directly into a string using ${} syntax

    let city = "Delhi";
    let country = "India";
    
    console.log(`I live in ${city}, ${country}`);
    • Expression Evaluation

      Template literals can evaluate expressions inside ${ }.

    Use Expressions Inside Template Literals

    Allows performing calculations directly within ${} inside a string

    let a = 10;
    let b = 20;
    
    console.log(`Sum of a and b is ${a + b}`);
    • Function Calls Inside Template Literals

      You can also call functions inside template literals.

    Using Function Calls Inside Template Literals

    Demonstrates calling a function directly within ${} in a string

    function greet() {
      return "Good Morning";
    }
    
    console.log(`${greet()}, Welcome to JavaScript`);
    • Multi-line Strings Using Template Literals

      Traditional strings cannot span multiple lines easily.

    Multiline Strings Using Template Literals

    Shows a cleaner way to write multiline strings compared to using \n

    // Traditional Way (Not Recommended)
    let text = "This is line one\nThis is line two";
    
    // Using Template Literals (Recommended)
    let text = `
    This is line one
    This is line two
    This is line three
    `;
    
    console.log(text);
    • Advantages:

      • No escape characters

      • Maintains formatting

      • Easy readability

      HTML Templates Using Template Literals

      Template literals are commonly used to generate HTML dynamically.

    Creating Dynamic HTML Using Template Literals

    Uses template literals to generate and insert HTML content dynamically

    let username = "Amit";
    
    let html = `
      <div class="card">
        <h2>Welcome ${username}</h2>
        <p>This is a dynamic card.</p>
      </div>
    `;
    
    document.body.innerHTML = html;
    • Conditional Logic Inside Template Literals

      Ternary operator can be used inside ${}.

    Using Conditional Logic Inside Template Literals

    Applies ternary operator within ${} to display dynamic content

    let isLoggedIn = true;
    
    let message = `
    User Status: ${isLoggedIn ? "Logged In" : "Guest"}
    `;
    
    console.log(message);
    • Template Literals with Arrays

    Access Array Values Inside Template Literals

    Using array elements within ${} in a string

    let fruits = ["Apple", "Banana", "Mango"];
    
    console.log(`First fruit is ${fruits[0]}`);
    • Traditional Strings vs Template Literals
      FeatureTraditional StringsTemplate Literals
      Quotes' or "Backticks
      Variable insertionUsing +Using ${}
      Multi-line supportDifficultEasy
      ReadabilityLowHigh
      Modern usageOldRecommended

      Common Mistakes

      • Using quotes instead of backticks

      • Forgetting ${ } for variables

      • Trying to use template literals in older browsers without support

      • Writing complex logic inside ${ }