Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
string
communitycreator

What are template literals in JavaScript?

Programming Bytes

Template Literals

Template literals allow you to embed JavaScript expressions inside a string.

To create a template literal, use backticks (``):

`I am a template string`

A template literal has three features:

  • Multi-line string
  • Interpolationinserts an expression inside a string
  • Tagged template literalcalls a function

1. Multi-line string

Before template literals, if we wanted to create a multi-line string, we would have to write:

console.log('Line 1 \n' + 'Line 2');

However, with template literals, this can be simplified to:

let str = `Line 1
Line 2`;
console.log(str);
// or 
console.log(`Line 1
Line 2`);

In essence, template literals make multi-line strings simpler.


2. Interpolation

Interpolation allows you to insert a valid JavaScript expression inside the template literal. Before evaluating the string, all the expressions are executed.

You can include an expression like ${expression}:

let a = 10;
let b = 20;
console.log(`Result = ${a + b}`); // Result = 30

Using a conditional expression:

var a = 10;
var b = 20;
console.log(` ${a > b ? a : b} is greater`); // 20 is greater

Using function calls inside of a template literal:

function getName() {
   return "JavaScript Jeep";
}
console.log(`Name => ${getName()}`); // Name => JavaScript Jeep

Printing ` using a template literal:

console.log(`\``); // `

Printing ${} using a template literal:

console.log(`$`); //$
console.log(`$\{}`); // ${}
console.log(`$${100}`); //$100
console.log(`$$\{}`); // $${}

// errors
//console.log(`${`); // Uncaught SyntaxError: Unexpected end of input

// you can't have an empty ${}
//console.log(`${}`); // Uncaught SyntaxError: Unexpected token '}'
//console.log(`$${}`); // Uncaught SyntaxError: Unexpected token '}'

3. Tagged Templates

Tagged templates allow you to call a function:

function tagFun(string, param1) {
   console.log(`String => ${string}`);
   console.log(`param1 => ${param1}`);
}
let a = 10;
tagFun`This is a ${a} test`;

// String => This is a , test
// param1 => 10

In the function above, all the strings are passed to the string parameter and the a is passed to param1.

Here’s another example:

function tagFun(string, param1, param2) {
   console.log(`string - ${string}`);
   console.log(`param1 = ${param1} param2 = ${param2}`);
}
var a = 10, b =20;
tagFun`a => ${a} b => ${b}`;

Instead of using multiple parameters, you can use a rest parameter:

function tagFun(string, ...params){
  console.log(params);
}
var a = 10, b = 20, c = 100;
tagFun`testing ${a} ${b} ${c} end`
// [10, 20, 100]

Here’s another example using destructing variables:

function testFun([str1, str2], value) {
   console.log(str1);
   console.log(str2);
}
testFun`This is ${10} a test`;

We can use tagged templates to create a function that will look like a normal English sentence:

function math([x, y], operation) { 
   return operation(Number(x), Number(y));
}
function plus(x, y) {
   return x + y;
}

In the above code, we have the math function, which takes 2 arguments, one array and one function. We call this method using the tagged template:

math`1 ${plus} 2`; // x=1, y=2, operation = plus; output is 3

Upon calling the math function, 1 is destructed to x, 2 is destructed to y, and the plus function is passed as a value to the operation argument. Inside the math function, we call the operation function with x and y as arguments.

function math([x, y], operation) { 
   return operation(Number(x), Number(y));
}
function plus(x, y) {
   return x + y;
}
console.log(math`1 ${plus} 2`);

RELATED TAGS

javascript
string
communitycreator
RELATED COURSES

View all Courses

Keep Exploring