{"id":24792,"date":"2024-03-01T00:04:33","date_gmt":"2024-02-29T23:04:33","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/domina-los-template-literals-en-javascript\/"},"modified":"2024-06-03T17:37:35","modified_gmt":"2024-06-03T16:37:35","slug":"domina-los-template-literals-en-javascript","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/","title":{"rendered":"Master Template Literals in JavaScript"},"content":{"rendered":"<p>The inverted comma, technically known as a grave accent (`), has taken a leading role in JavaScript since the arrival of ES6 (ECMAScript 6). This syntax not only improves the readability of the code when working with text strings but also introduces a powerful tool: template literals. In this walkthrough, we&#039;ll explore how to get the most out of this feature, showing its basic syntax and moving toward more elaborate uses that will simplify your code and make it more expressive.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Sintaxis_Basica_de_Template_Literals\" >Basic Template Literals Syntax<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Insertar_Variables\" >Insert Variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Expresiones_Complejas\" >Complex Expressions<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Multilinea_y_Formato_de_Texto\" >Multiline and Text Format<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Etiquetas_para_Template_Literals\" >Tags for Template Literals<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Funcion_Etiqueta_Basica\" >Basic Label Function<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Template_Literals_y_Seguridad\" >Template Literals and Security<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Usos_Practicos_de_Template_Literals\" >Practical Uses of Template Literals<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Creacion_Dinamica_de_HTML\" >Dynamic HTML Creation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Plantillas_de_Mensajes_y_Traducciones\" >Message and Translation Templates<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-template-literals-in-javascript\/#Conclusiones_y_Recursos\" >Conclusions and Resources<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Sintaxis_Basica_de_Template_Literals\"><\/span>Basic Template Literals Syntax<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The essence of a template literal in JavaScript lies in the use of backticks to delimit strings, instead of the single or double quotes that have traditionally been used. The main difference lies in the ability of template literals to interpret embedded expressions, which is done through the syntax <code>${expression}<\/code>. This allows any valid JavaScript expression to be easily evaluated and concatenated into a text string.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Insertar_Variables\"><\/span>Insert Variables<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Imagine that you have two variables and you want to construct a sentence that includes them:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">let name = &quot;Nelko&quot;; let job = &quot;developer&quot;; \/\/ Without template literals let presentation = &quot;Hello, I am &quot; + name + &quot; and I am &quot; + job + &quot;.&quot;; console.log(presentation); \/\/ &quot;Hello, I&#039;m Nelko and I&#039;m a developer.&quot; \/\/ With template literals let improvedpresentation = `Hello, I&#039;m ${name} and I&#039;m ${work}.`; console.log(improvedpresentation); \/\/ &quot;Hello, I&#039;m Nelko and I&#039;m a developer.&quot;<\/code><\/pre>\n<p>As you can see, template literals simplify the concatenation of variables within a text string.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Expresiones_Complejas\"><\/span>Complex Expressions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Beyond inserting variables, you can perform operations directly within these interpolations:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">let price = 20; let quantity = 3; \/\/ Calculating within a template literal let message = `The total is: ${price * quantity} dollars.`; console.log(message); \/\/ &quot;The total is: 60 dollars.&quot;<\/code><\/pre>\n<p>This example shows how a mathematical operation is solved directly within the template literal, eliminating the need for additional variables.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Multilinea_y_Formato_de_Texto\"><\/span>Multiline and Text Format<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>One of the headaches when working with strings in JavaScript was managing multiline strings. Before ES6, maintaining the desired format could be complicated and unintuitive. Template literals solve this by allowing line breaks to be inserted directly into the text:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">\/\/ Multiline format with template literals let poem = `Roses are red, Violets are blue, Sugar is sweet, And so are you.`; console.log(poem);<\/code><\/pre>\n<p>The output will retain exact formatting, including line breaks, which is ideal for generating HTML code or handling long text where formatting is important.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Etiquetas_para_Template_Literals\"><\/span>Tags for Template Literals<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>An advanced feature of template literals are tags. These allow the template to be processed before it is transformed into a text string, offering a significant level of control and customization.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Funcion_Etiqueta_Basica\"><\/span>Basic Label Function<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>A label function is defined as follows:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">function tag(strings, ...values) { \/\/ Processing the template literal } \/\/ Using the tag function let name = &quot;Nelko&quot;; let message = label`Hello ${name}!`;\n<\/code><\/pre>\n<p>Inside the function <code>label<\/code>, <code>strings<\/code> is an array with the text segments and <code>values<\/code> are the interpolated values. Here you can perform operations such as sanitizing content, translation, or even the creation of DSLs (Domain Specific Languages).<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Template_Literals_y_Seguridad\"><\/span>Template Literals and Security<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In the context of security, template literals offer significant advantages. For example, injecting data directly into traditional strings can be a source of XSS (Cross-Site Scripting) vulnerabilities when working with HTML. However, if you use a proper method to sanitize interpolated values in a template literal, you can avoid many of these security issues.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Usos_Practicos_de_Template_Literals\"><\/span>Practical Uses of Template Literals<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Creacion_Dinamica_de_HTML\"><\/span>Dynamic HTML Creation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Template literals are ideal for creating HTML fragments dynamically:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">let user = { name: &amp;quot;Nelko&amp;quot;, occupation: &amp;quot;Developer&amp;quot; }; let cardHtml = `\n  &lt;div class=&quot;card&quot;&gt;\n    &lt;h2&gt;${user.name}&lt;\/h2&gt;\n    &lt;p&gt;${user.occupation}&lt;\/p&gt;\n  &lt;\/div&gt;\n`; document.body.innerHTML += cardHtml;<\/code><\/pre>\n<p>With a few lines of code, we can insert an HTML element that includes our user data.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Plantillas_de_Mensajes_y_Traducciones\"><\/span>Message and Translation Templates<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>If you handle internationalization in your applications, template literals can be of great help to structure message templates and variables that will later be translated:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">let quantity = 3; let message = `Do you have ${amount} ${amount === 1 ? &quot;message&quot; : &quot;messages&quot;} new`; console.log(message); \/\/ &quot;You have 3 new messages&quot;<\/code><\/pre>\n<p>In this case, the use of the ternary operator within the template literal makes it easier to select a singular or plural form depending on the context, a very useful feature in i18n.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusiones_y_Recursos\"><\/span>Conclusions and Resources<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Template literals represent a significant improvement for working with text strings in JavaScript. They facilitate readability, allow the construction of multiline strings, and the insertion of variables and expressions in a simple and direct way. Additionally, the tags feature opens up a world of possibilities for advanced template processing.<\/p>\n<p>If you want to delve deeper into this topic or discover other development techniques, I invite you to explore <a href=\"https:\/\/nelkodev.com\/en\/\">NelkoDev<\/a>, where I constantly share resources, tutorials, and tips that will help you on your learning path in web development.<\/p>\n<p>Do you have questions or need help with your project? Don&#039;t hesitate to get in touch via <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">NelkoDev Contact<\/a>, I will be happy to help you resolve your doubts and contribute to the success of your project. Let&#039;s program!<\/p>","protected":false},"excerpt":{"rendered":"<p>La comilla invertida, conocida tecnicamente como acento grave (`), ha tomado un papel protagonista en JavaScript desde la llegada de ES6 (ECMAScript 6). Esta sintaxis no solo mejora la legibilidad del c\u00f3digo al trabajar con cadenas de texto sino que tambi\u00e9n introduce una potente herramienta: los template literals. En este recorrido, exploraremos c\u00f3mo sacar el [&hellip;]<\/p>","protected":false},"author":1,"featured_media":24793,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420],"tags":[205,1473,185,1569,221,1570],"class_list":["post-24792","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-blog","tag-domina","tag-javascript","tag-literals","tag-los","tag-template"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24792","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=24792"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/24792\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/24793"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=24792"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=24792"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=24792"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}