Template String in ES6 Javascript

izzycious

Ishaq Nasir

Posted on June 27, 2022

Template String in ES6 Javascript

Using template string is a better form than using string concatenation making your JavaScript more readable and easy to understand.

By the end of this article you'll understand;

  • How to use Template strings

  • Why use it over string concatenation

Let's get into it

let lastName = 'John';
let firstName = 'Doe';
let age = prompt('What is your age: '); // prompt user to add his age

Enter fullscreen mode Exit fullscreen mode

Before the advent of ECMA script, to console the output of the above code trying to concatenate them into a piece.

let result = lastName + ' ' + firstName + 'is' + age + ' ' + 'years old';
console.log(result)

Enter fullscreen mode Exit fullscreen mode

output

//output will be after the user has been prompted to add their age

//John Doe is 25 years old

Enter fullscreen mode Exit fullscreen mode

This is a cool way to string variables together, but assume you work on a large code base that has plenty of variables declared.
How you make this shorter and easily readable is by using template strings which can also be termed template literals.

Using the template string

let result = `${lastName} ${firstName} is ${age} years old`;
console.log(result);
Enter fullscreen mode Exit fullscreen mode

output

// same application after prompting user information

// John Doe is 25 years old.
Enter fullscreen mode Exit fullscreen mode

The template string makes code shorter and gives the developer the quickest option to call the variables into action making it readable for the developer or whomsoever is reading the code.

`

💖 💪 🙅 🚩
izzycious
Ishaq Nasir

Posted on June 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related