Welcome Guest! (App Version 3.1)

websitnero logo name

Template Literals

Template Literals in ES6

The feature of Template literals has been introduced in ES6 and this is one package with multiple benefits.

"Template Literals" define a new way to declare and work with strings. This method is more powerful and useful than the earlier way of string declaration in ES5. You will use this feature a lot, even while working with Angular or React.

Template literals use the ` ... ` quotes (left to key 1 in keyboard) for declaring strings. Whatever you write within these quotes is rendered as it is on the console screen (even spaces and text in multiple lines). Also, you don't need to use "\n" for going to new line.

Template literals also provide an easy way to interpolate variables and expressions within strings.

Multiple Lines by Template Literals

Lets see what happens if you try to print multiple lines in a string the old way:

var str = "first line 
       second line";

Output: Error: Invalid or unexpected token

Now, lets try to do the same using ES6 (Template Literals) using the ` ` quotes:

var str = `first line 
       second line`;


"first line
        second line"

Variables and Expressions Interpolation

As mentioned earlier, you can also use variables and expressions and get calculated results using ` ` quotes. Look at the example below:

let name = "Peter Martin";
let age = 29;
let country = "USA";
let message = "Good Bye!";
let color = "blue";

let result = (`Hi, ${name},
You are is ${age} and you are from ${country}
Your favorite color is ${color}
After three years you will be ${age+3} years old
        ${message} ...`)



"Hi, Peter Martin,
You are is 29 and you are from USA
Your favorite color is blue
After three years you will be 32 years old
        Good Bye! ..."

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.