Skip to main content

Command Palette

Search for a command to run...

Temperal Literals

Updated
2 min read

Problem with traditional string concatenation

Before ES6, JavaScript used + to combine strings

const name = "Ayush";
const age = 20;

const message = "My name is " + name + " and I am " + age + " years old.";

const text = "This is line 1\n" +
             "This is line 2\n" +
             "This is line 3"; //multi line string

Issues:

  • Hard to read (especially with many variables)

  • Error-prone (missing spaces, quotes)

  • Difficult for multi-line strings

  • Debugging becomes messy in long expressions

Template Literal Syntax (ES6)

Template literals use backticks (` `) instead of quotes:

const message = `My name is Ayush`;

Whatever written in those backticks is treated similarly that is written in quotes, but coming to embedding variables, its easy to write, read, and debug.

Embedding Variables (String Interpolation)

Instead of concatenation, use ${}:

const name = "Ayush";
const age = 20;

const message = `My name is \({name} and I am \){age} years old.`;

const text = `This is line 1
This is line 2
This is line 3`;//multi line string

Advantages:

  • Cleaner syntax

  • No need for +

  • Automatic spacing and formatting

  • Can include expressions:

const result = `Next year I will be ${age + 1}`;

Use Cases in Modern JavaScript

Template literals are widely used in:

1. Dynamic HTML

const user = "Ayush";
const html = `<h1>Welcome, ${user}</h1>`;

2. API Responses / Logging

console.log(`User \({user} logged in at \){new Date()}`);

3. SQL / Query Building (careful with security)

const query = `SELECT * FROM users WHERE name = '${user}'`;

4. Styled Components / UI frameworks

const style = `color: ${isActive ? "green" : "red"}`;

Comparison: Old vs Template Literals

Feature Old Concatenation Template Literals
Syntax "Hello " + name Hello ${name}
Readability ❌ Low ✅ High
Multi-line ❌ Hard ✅ Easy
Expressions ❌ Limited ✅ Powerful
Maintenance ❌ Difficult ✅ Simple

Conclusion

Temperal literals are an upgrade to the language making it better to use.