Mwendwa Bundi Emma
Mwendwa Bundi Blogs

Mwendwa Bundi Blogs

JavaScript Template Literals Explained

JavaScript Template Literals Explained

Mwendwa Bundi Emma's photo
Mwendwa Bundi Emma
·Feb 16, 2022·

2 min read

Template literals is a feature in ECMAScript which uses backticks ` as its syntax.

Good thing is it makes creating complex strings easier and you do not need to escape quotes in your string. Look at these:

let word = `he said, "bring them back"`;

However, remember if your string itself has backticks, you will need to escape in a backslash \ .

String Expression Interpolation

Assigning variables and expressions inside your template literal is known as Interpolation

The syntax we use during interpolation is ${...}.

How?

var first = 22;
var second = 23;
console.log(`They brought in ${first+second} books`);

Output: They brought in 45 books

In the above case you see that we used the interpolation syntax and the + expression.

const sum = (x, y) => x + y
const x = 12
const y = 10
const example = `Sum of ${x} and ${y} should be ${sum(x, y)}.`

console.log(example)

Output:

sum of 12 and 10 should be 120.

So much flexibility with your string, right?

Now, look at this other example

const needs = {
  one: "classic poems",
  two: 12
};

const example = `I love to read ${needs.one}

I have read ${needs.two} books this year.`;

console.log(example);

Output:

I love to read classic poems

I have read 12 books this year.

The above example did show a case of multiline but let us explain it better below:

Remember, in my previous on normal strings we had to use the \n character to get a newline.

Look at these:

const needs = `I do love poems
reading and writing them as well
depends on my mood.`

console.log(needs);

Output:

I do love poems

reading and writing them as well

depends on my mood

Good to note that the whitespace character works just as fine in writing multiline strings with template literals.

You quickly learn performing manipulations with your strings and increasing your options whilst working with strings is more simplified by template literals. Such a good feature for programmers.

That's it for today. Today's quote, "You cannot swim for new horizons until you have courage to lose sight of the shore" William Faulkner.

Let me know your thoughts in the comment section. I'll see you in my next article. Bye