This page looks best with JavaScript enabled

Template Literals in Javascript

 ·   ·  ☕ 1 min read

Template literals provide an easily readable way to embed expressions within string literals.

For example -

1
2
3
const thirdSmartPlanet = "earth";
const fact = `${thirdSmartPlanet} is flat`;
console.log("fact: ", fact); // fact:  earth is flat

Earlier, you had to combine strings and variable like so -

1
const fact = thirdSmartPlanet + " is flat";

Hope you observed the backtick (‘`’)?

Not only that -

  • You can output on multiple lines without breaking a sweat

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    const statement = `dogs
      are
          our
              best
                 friends`;
    console.log(statement);
    /* output
    dogs
      are
          our
              best
                 friends
    */
    
  • Evaluate expressions

    1
    2
    3
    4
    
    const a = 3;
    const b = 2;
    console.log(`sum of a and b is ${a + b}`);
    // sum of a and b is 5
    
  • Nest template literals (though I don’t know why you would want to do that)

    1
    2
    3
    4
    5
    
    const a = 3;
    const b = 2;
    console.log(
      `sum of a and b is ${`${a + b > 10 ? "more than 10" : "less than 10"}`}`
    );
    
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things