Template Literals

What is it?

Template literals allow you to embed variables directly inside strings.

Before ES6:

const name = "Jithu";
const age = 22;

console.log(
    "My name is " + name + " and I am " + age + " years old."
);

Output:

My name is Jithu and I am 22 years old.

ES6 Way

Use backticks (`)

const name = "Jithu";
const age = 22;

console.log(
    `My name is ${name} and I am ${age} years old.`
);

Output:

My name is Jithu and I am 22 years old.

Multiple Lines

Before ES6:

const text =
"Hello\n" +
"World";

After ES6:

const text = `
Hello
World
`;

console.log(text);

Output:

Hello
World

Expression Inside Template Literal

const a = 10;
const b = 20;

console.log(`Sum = ${a + b}`);

Output:

Sum = 30