Saturday, 22 December 2018

What are template literals (or) template strings in JavaScript

Template literals are introduced in ECMAScript 2015, These are used to embed expressions. Template literals are enclosed by the back-tick (` `).

Syntax
`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

As you see the above syntax, template strings can contain place holders, these places holders are specified by $ sign followed by curly braces ${}.

Let’s see by an example.

HelloWorld.js
var x = 10;
var message = "Good Morning";

var y = `Value of x is : ${x}`;
var msg = `Value of message is : ${message}`;

console.log(y);
console.log(msg);


Output

Value of x is : 10

Value of message is : Good Morning

Represent multi line strings using template literals
Usually multi line strings are represented using \.

var str = "Hello PTR, \
How are you. \
How is life going on!!!!!!";

You can even write multi line strings using template literal like below.

var str = `Hello PTR,
How are you.
How is life going on!!!!!!`;

Evaluating Expressions
You can evaluate an expression using placeholders. Places holders are specified by $ sign followed by curly braces ${}.

HelloWorld.js

var x = 10;
var y = 20;

console.log(`Sum of ${x} and ${y} is ${x+y}`);


Output
Sum of 10 and 20 is 30


Previous                                                 Next                                                 Home

No comments:

Post a Comment