Javascript ES6 — Template Literals # 4

To create a string in javascript you’ve two choices, single quote or double
quotes, in case of a raw text you can create your string with no problem.

const message = "Hello";

Once you want to add a variable into this string, you’ve to use the plus sign to
do the concatenation, let’s create a variable name, and concatenate its value to
the message variable.

const name = "John Doe";
const message = "Hello, " + name;

Console.log the result


This way of forming strings can’t be practical in case of a long string.
Template literals solve this problem, by allowing you embedding expressions in a
simpler way, and some of the pros are, you can use multi-line string and string
interpolation and avoid long string concatenation. To create a template literal
is very simple, instead of single quote or double quotes, you use backtick,
let’s change the double quote in our variables to follow a template string.

const name = `John Doe`;
const message = `Hello` + name;

Expression interpolation

You don’t use concatenation to include an expression within a template string,
instead, you include an expression into a string, by using the dollar sign plus
the open and closed brackets, that follow this logic

// ${expression}

the ${} syntax allows us to put the value of an expression and
it’ll produce the value, let’s remove the plus sign and move the
name variable into the Hello string.

const message = `Hello ${name}`;

The variable name doesn’t include any expression, it can be a
regular string, you can avoid using backtick and use the double quote instead.

const name = "John";

An expression can be a variable that contains a string, or an evaluated
expression, as an example lets calculate the tax of a specific price. Go for a
price equal to 120 and a tax of 20 percent.

const price = 120;
const tax = 20;

Now let’s use template literals to display the total, so const total equal to,
open and close the backtick, add the message The total to pay:, now
you’ve to include the expression, dollar sign and open and close the brackets
${}, you want to calculate the tax, so the expression will be,
price times tax divided by 100.

const total = `The total to pay: ${(price * tax) / 100}`;

Console log the total


I can even simplify it, by replacing the expression, by a variable

const taxFormula = (price * tax) / 100;
const total = `The total to pay: ${taxFormula}`;

Multi-line strings

If you create a string using the traditional way, and you want it to be on
multiple lines, you’ll be forced to use the backslash and n character or the new
line character in a specific position.

const message = "This has to be\n on two lines"

So you can imagine if the string is longer than that, creating a string with
multiple lines can return to a nightmare. With template literal string, you just
go ahead an add the new line as you write it, replace double quotes by
backticks, remove the new line character, and it’ll create a string with a new
line, so no need of the new line character.

const message = "This has to be
on two lines"

HTML Templates

These two features of multi-line and using an expression to add content into our
strings can be very helpful to use for HTML templates in our code, let’s do an
example of getting data from an imaginary API, let’s create an object USER_INFOS
that have some values, firstName, lastName and age.

const USER_INFOS = {
    firstName: "John",
    lastName: "Doe",
    age: 20

Let’s create the markup that would show the student info, so create a new
function createMarkup that get the data as a parameter
and it will return an unordered list of three elements

const createMarkup = data => {
 return `
`; };

The data we’ll get is the first name, last name, and age, so add the dollar and
the bracket signs to create an expression and from the object data get the
firstName, same for the lastName and age.

const createMarkup = data => {
 return `
  • ${data.firstName}
  • ${data.lastName}
  • ${data.age}
`; };

Let’s take a look to the formated string, go for a variable
formattedString equal to the returned value of
createMarkup function, and for the argument
USER_INFOS, and console log the formattedString

const formattedString = createMarkup(USER_INFOS);

This is an easy way to use templates without having to use any specific library.

Leave a Reply

Your email address will not be published. Required fields are marked *