Wednesday, March 24, 2021

How to use JavaScript template strings

JavaScript Template Strings are another way to create and combine strings. The technique is simple once you know the syntax.

Here is a code snippet with three string variables:

const str1 = 'Coffee ';
const str2 = 'and ';
const str3 = 'code';

One way to combine the strings is the concat() function:

const combinedStr = str1.concat(str2, str3);
console.log(combinedStr); // outputs: Coffee and code

Another way to combine them is the + operator:

const combinedStr = str1 + str2 + str3;
console.log(combinedStr); // outputs: Coffee and code

And here is how to combine the strings with a JavaScript Template String:

const combinedStr = `${str1}${str2}${str3}`;
console.log(combinedStr); // outputs: Coffee and code

To create a Template String:

  1. Start and end the Template String with a backtick (`).
  2. Put your variable, expression, or data between ${ and }. JavaScript evaluates this value.
  3. Other characters in the Template String are just literal characters.
Here is another Template String example that combines literal characters with a random number:

const num = Math.random();
const combinedStr = `Here is a random number: ${num}.`;
console.log(combinedStr); // sample output: Here is a random number: 0.07571510037185902.

JavaScript Template Strings are another way to combine and create strings. The technique is convenient and simple. Some JavaScript lint tools prefer Template Strings over string concatenation. So that is another reason to learn them.









No comments:

Post a Comment

What is Git Markdown?

Git Markdown is a markup language that creates HTML-like documents for web-based Git repos like GitHub, GitLab, and Bitbucket. The documents...