{"id":3106,"date":"2017-09-30T16:42:53","date_gmt":"2017-09-30T11:12:53","guid":{"rendered":"https:\/\/code4developers.com\/?p=3106"},"modified":"2017-09-30T16:44:17","modified_gmt":"2017-09-30T11:14:17","slug":"javascript-template-literals","status":"publish","type":"post","link":"https:\/\/code4developers.com\/javascript-template-literals\/","title":{"rendered":"Javascript: What Are Template Literals?"},"content":{"rendered":"<p>ES6 introduced two types of literals: Template Literals and Tagged Template Literals to tag Template Literals. In this post, we cover both of them in depth!<\/p>\n<p>In ES6, two types of literals were introduced:<\/p>\n<ol>\n<li>Template Literals for string concatenation and expression embedding in a string<\/li>\n<li>Tagged Template Literals to tag the Template Literal in a function so the literal can be evaluated in the function<\/li>\n<\/ol>\n<p><!--more--><\/p>\n<h3 id=\"template-literals\">Template Literals<\/h3>\n<p>Let\u2019s assume that you need to do the string concatenation with a dynamic expression or with the value of a variable. Take a look at the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">var foo = 9;\r\nvar result = `Result = ${foo}`;\r\nconsole.log(result);<\/pre>\n<p>Here, you see you\u2019ll need to embed the value of variable foo in a string literal. In ES6, you can do this using Template Literals, as shown in the code listing above. Template Literals are mainly used for the following purposes:<\/p>\n<ul>\n<li>String concatenation<\/li>\n<li>Creating multi-line strings<\/li>\n<li>Embedding expressions<\/li>\n<li>Using string interpolation<\/li>\n<\/ul>\n<p>In the code above, we are embedding the expression\u00a0foo\u00a0in the string result. To use Template Literals:<\/p>\n<ol>\n<li>Template Literals are created inside back-tick (`) characters.<\/li>\n<li>In Template Literals, placeholders are created using the\u00a0${expression}\u00a0symbol. At runtime, the expression will be evaluated and replaced in the placeholders.<\/li>\n<li>In template Literals, the expression can be embedded using\u00a0${expression}. This is also called an expression interpolation.<\/li>\n<\/ol>\n<p>Using Template Literals, let us create some expression interpolation. Consider the following code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">var num1 = 9;\r\nvar num2 = 7;\r\nvar result = `Result = ${num1 + num2}\u00a0 and twice of result = ${2 * (num1 + num2)}`;\r\nconsole.log(result);<\/pre>\n<p>To create expression interpolation here, we are using the Template Literal. You\u2019ll also notice the string is broken into multiple lines. If required, you can create\u00a0a nested template also.<\/p>\n<h3 id=\"tagged-template-literals\"><strong>Tagged Template Literals<\/strong><\/h3>\n<p>ES6 allows you to tag template literals, meaning you can parse that inside a function. So, if you use Tagged Template Literals, JavaScript will not immediately assign them to a variable, and rather parse them in a function. Let\u2019s see an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">function sayHello() {\r\n\r\n\r\n\r\n\r\n\r\n}\r\nconst name = \"foo\";\r\nconst country = \"India\";\r\nconst result = `hey ${name} welcome to ${country}`;\r\nconsole.log(result);\r\n\r\n<\/pre>\n<p>Now let\u2019s assume that in the sayHello function, you want to pass a template literal, perform some manipulation, and return a result. To do that, you can tag the template literal to function as shown below:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">function sayHello() {\r\n\r\n\r\n\r\n\r\n\r\n}\r\nconst name = \"foo\";\r\nconst country = \"India\";\r\nconst result = sayHello`hey ${name} welcome to ${country}`;\r\nconsole.log(result);<\/pre>\n<p>Here, you have tagged the template literal to the function\u00a0sayHello. In Tagged Template Literals, the function gets the following parameters:<\/p>\n<ol>\n<li>The first parameter is a string array<\/li>\n<li>The second parameter onwards are interpolated values<\/li>\n<\/ol>\n<p>Let&#8217;s modify the\u00a0sayHello\u00a0function to work with these parameters. Consider the code below:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">function sayHello(strings, name, country) {\r\n\r\n\u00a0\u00a0\u00a0 console.log(strings[0]); \/\/hey\r\n\u00a0\u00a0\u00a0 console.log(strings[1]);\/\/ welcome to\r\n\u00a0\u00a0\u00a0 console.log(strings[2]); \/\/ empty string\r\n\u00a0\u00a0\u00a0 console.log(strings[3]); \/\/ undefined\r\n\r\n}\r\nconst name = \"foo\";\r\nconst country = \"India\";\r\nconst result = sayHello`hey ${name} welcome to ${country}`;\r\nconsole.log(result);<\/pre>\n<p>As you can see, all strings of the Template Literal will be passed as the first parameter of the function. In the other two parameters (name and country), interpolated values will be passed. So, the name will contain foo and the country will contain India. Now, let\u2019s see the code below:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">function sayHello(strings, name, country) {\r\n\u00a0\u00a0\u00a0 var res = '';\r\n\u00a0\u00a0\u00a0 var ctrstring = '';\r\n\r\n\u00a0\u00a0\u00a0 if (country == \"India\") {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ctrstring = \" visit Delhi\";\r\n\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 else if (country == \"USA\") {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ctrstring = \" visit NY\";\r\n\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 else {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ctrstring = \" visit any where \";\r\n\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 res = strings[0] + name + strings[1] + country + ctrstring;\r\n\u00a0\u00a0\u00a0 return res;\r\n}\r\n\r\nconst name = \"foo\";\r\nconst country = \"India\";\r\nconst result = sayHello`hey ${name} welcome to ${country}`;\r\nconsole.log(result); \/\/ hey foo welcome to India visit Delhi<\/pre>\n<p>In the above code snippet, we are checking the value of the interpolated parameter\u00a0country\u00a0and then creating a new string and returning that. You will get the expected output, however, there is one problem with the above approach: you are mapping all interpolated parameters in named parameters. This could cause problems for the dynamic number of interpolated parameters. This can be solved using JavaScript REST Parameters. So we should rewrite the above code as it appears below:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\" data-enlighter-theme=\"classic\">function sayHello(strings, ...params) {\r\n\u00a0\u00a0\u00a0 var res = '';\r\n\u00a0\u00a0\u00a0 var ctrstring = '';\r\n\r\n\u00a0\u00a0\u00a0 if (country == \"India\") {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ctrstring = \" visit Delhi\";\r\n\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 else if (params[1] == \"USA\") {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ctrstring = \" visit NY\";\r\n\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 else {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ctrstring = \" visit any where \";\r\n\u00a0\u00a0\u00a0 }\r\n\u00a0\u00a0\u00a0 res = strings[0] + params[0] + strings[1] + params[1] + ctrstring;\r\n\u00a0\u00a0\u00a0 return res;\r\n}\r\nconst name = \"foo\";\r\nconst country = \"India\";\r\n\r\nconst result = sayHello`hey ${name} welcome to ${country}`;\r\nconsole.log(result); \/\/ hey foo welcome to India visit Delhi<\/pre>\n<p>As you see, you can combine Rest Parameters and Tagged Template Literals for better use cases.<\/p>\n<h4 id=\"conclusion\"><strong>Conclusion<\/strong><\/h4>\n<p>ES6 introduced two types of literals: Template Literals for string concatenation and embedding expressions in a string and Tagged Template Literals to tag Template Literals in a function so the literal can be evaluated in the function. And in this post, we covered both of them in-depth!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>ES6 introduced two types of literals: Template Literals and Tagged Template Literals to tag Template Literals. In this post, we cover both of them in depth! In ES6, two types&hellip;<\/p>\n","protected":false},"author":7,"featured_media":2672,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[2],"tags":[60,22,58,61,59],"powerkit_post_featured":[],"class_list":{"0":"post-3106","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"tag-es6","9":"tag-javascript","10":"tag-literals","11":"tag-tagged-template-literals","12":"tag-template-literals"},"jetpack_featured_media_url":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/06\/thumb-1-e1498942297714.png?fit=240%2C269&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8NAi4-O6","jetpack-related-posts":[{"id":3165,"url":"https:\/\/code4developers.com\/pug\/","url_meta":{"origin":3106,"position":0},"title":"Pug","author":"Arif Khoja","date":"December 15, 2017","format":false,"excerpt":"Pug is a template language for Javascript that I have grown to enjoy a lot. My impression is that a lot of people use it, if they use a template engine for server side rendering using Node. The big question is if you need it or not in 2017. I\u2026","rel":"","context":"In \"Node\"","block_context":{"text":"Node","link":"https:\/\/code4developers.com\/tag\/node\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/12\/PugJs.png?fit=225%2C225&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":3321,"url":"https:\/\/code4developers.com\/spread-syntax-in-javascript\/","url_meta":{"origin":3106,"position":1},"title":"Spread syntax (three dots) in JavaScript","author":"Yatendrasinh Joddha","date":"March 21, 2018","format":false,"excerpt":"Spread syntax which is used by typing three dots (...) in JavaScript. It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls\u00a0or elements for array are expected. It can also be used for an\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":3230,"url":"https:\/\/code4developers.com\/whats-new-ecmascript-2018\/","url_meta":{"origin":3106,"position":2},"title":"What\u2019s new in ECMAScript 2018","author":"Arif Khoja","date":"February 16, 2018","format":false,"excerpt":"Four new feature proposals for the specification underlying JavaScript are finalized and four others are under consideration ECMAScript, the standard specification underlying JavaScript, is on track for a new release, likely in June. So far, four proposals have been finalized for inclusion in the ECMAScript 2018 specification, said Zibi Braniecki,\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"ecma script","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/ecma.png?fit=400%2C277&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":2662,"url":"https:\/\/code4developers.com\/ecmascript-5-strict-mode-json\/","url_meta":{"origin":3106,"position":3},"title":"ECMAScript5 Strict Mode, JSON, and More&#8230;.","author":"Arif Khoja","date":"June 25, 2017","format":false,"excerpt":"Introduction There are a number of other new features and APIs that need attention, as well. The largest of which are\u00a0Strict Mode\u00a0and native\u00a0JSON\u00a0support. Strict Mode Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a \u201cstrict\u201d operating context. This\u2026","rel":"","context":"In &quot;JavaScript&quot;","block_context":{"text":"JavaScript","link":"https:\/\/code4developers.com\/category\/javascript\/"},"img":{"alt_text":"javascript","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/10\/javascript.jpg?fit=750%2C422&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":3007,"url":"https:\/\/code4developers.com\/angular-4-components\/","url_meta":{"origin":3106,"position":4},"title":"Angular 4 Components","author":"Nisarg Dave","date":"July 28, 2017","format":false,"excerpt":"In this article, we will discuss about what is a component in Angular 4? In Angular 4 everything is component. Rather we can say components are the basic building blocks of Angular 4 applications. Component based web development is the future of web development.\u00a0The advantage of the component-based approach is\u2026","rel":"","context":"In &quot;Angular&quot;","block_context":{"text":"Angular","link":"https:\/\/code4developers.com\/category\/angular\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/code4developers.com\/wp-content\/uploads\/2017\/06\/angular-2.png?fit=240%2C240&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":2613,"url":"https:\/\/code4developers.com\/ui-routing-basics\/","url_meta":{"origin":3106,"position":5},"title":"UI-Routing &#8211; Basics","author":"Arif Khoja","date":"June 17, 2017","format":false,"excerpt":"Introduction In the present scenario, AngularJS is the most trusted framework for the creation of Single Page Applications (SPA), and UI-Routing is one of the most important aspects. We want to keep our navigation feeling like a normal site and want to load the pages without refreshing the Browser. For\u2026","rel":"","context":"In &quot;AngularJs&quot;","block_context":{"text":"AngularJs","link":"https:\/\/code4developers.com\/category\/angularjs\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/3106","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/comments?post=3106"}],"version-history":[{"count":6,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/3106\/revisions"}],"predecessor-version":[{"id":3112,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/posts\/3106\/revisions\/3112"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media\/2672"}],"wp:attachment":[{"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/media?parent=3106"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/categories?post=3106"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/tags?post=3106"},{"taxonomy":"powerkit_post_featured","embeddable":true,"href":"https:\/\/code4developers.com\/wp-json\/wp\/v2\/powerkit_post_featured?post=3106"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}