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
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)
output
//output will be after the user has been prompted to add their age
//John Doe is 25 years old
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);
output
// same application after prompting user information
// John Doe is 25 years old.
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.
`
Top comments (0)