DEV Community

Abhishek sahni
Abhishek sahni

Posted on

Write cleaner code with Template Literals in JavaScript

We use template literals to write clean and readable code because traditional string concatenation has problem of readability.

Code Example :

Without template literals

const name = "John"; const age = 20;

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

console.log(message);
Enter fullscreen mode Exit fullscreen mode

To many "+" sign

Difficult to understand.

With Template literals

const name = "John";
const age = 20;

const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
Enter fullscreen mode Exit fullscreen mode

How to write Template literals (syntax) :

We use backticks \ to write template literal.

Inside the backticks you can embed(insert) your variables and valid JavaScript expression.

// use of variables inside the string.
const message = `My name is ${name} and I am ${age} years old.`;

//valid JavaScript expression inside the string.
console.log(`Sum is ${a + b}`);
Enter fullscreen mode Exit fullscreen mode

So what are template literals ?

In JavaScript, template literals(also known as template strings) . It allows string interpolation and multi-line string.

string interpolation : You can can use variables and any valid JavaScript expression inside the sting using ${expression}.

Using string interpolation

const name = "Abhi";
const age = 20;

// Using template literals
const message = `My name is ${name} and I am ${age} years old.`;

console.log(message);
Enter fullscreen mode Exit fullscreen mode

You can also write valid JavaScript expressions.

const a = 5;
const b = 10;

console.log(`Sum is ${a + b}`);
Enter fullscreen mode Exit fullscreen mode

multi-line string : Template literals preserve line breaks as you write inside the string .

Eliminating the need the escape characters like \n.

const text = `This is line 1
This is line 2
This is line 3`;

console.log(text);
Enter fullscreen mode Exit fullscreen mode

No need to use \n because in automatically preserve space.

Same Code without template literal (for comparison)

const name = "Abhi";
const age = 20;

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

const text = "This is line 1\nThis is line 2\nThis is line 3";

console.log(message);
console.log(text);
Enter fullscreen mode Exit fullscreen mode

Less readable and confusing.

Conclusion :

In this blog, we discussed template literals in JavaScript. We explored advanced features such as string interpolation and multi-line strings with practical code examples.

We also compared template literals with traditional string concatenation to understand how they improve readability and simplify code writing.

Top comments (0)