UI5
No Comments

6 Must Known New Features in ES6 – Part 2: Template Strings

ES6 part 2.

These are the newest and most crucial features in ES6 or also known as ECMAScript 6, ES2015, or JavaScript 6. This series of articles explains them super simple for you. Plus, each article states how to use the specific feature at its best.

This is article 2 of the series. It is about Template Strings. Template strings are the new way to write Strings in JavaScript including the integration of variables without concatenation. So cool!

Template strings are the new way to write Strings in JavaScript. Before ES6 Strings that contain for example HTML code have been written in this way …

let sHTML = '<div class="foo"><p id="bar">Paragraph Text</p></div>';

… or in this way with \ to get a more beautiful HTML output …

let sHTML = '<div class="foo"> \' + '<p id="bar">Paragraph Text</p> \' + '</div> \';

… or like this to code HTML more beautiful in JavaScript …

let aHTML = [
  '<div class="foo">',
    '<p id="bar">Paragraph Text</p>',
  '</div>'
].join('');

But a console.log(aHTML); of the above still looks like that:

<div class="foo"><p id="bar">Paragraph Text</p></div>

But now with ES6 it is possible to use those instead of these . Those are called a Template String. And by these it is possible to write for among other things beautiful HTML code in JavaScript:

let sHTML = `
  <div class="foo">
    <p id="bar">Paragraph Text</p>
  </div>
`;

The Template String will be outputted exactly the way it is initialized. All line breaks and white spaces. So a console.log(sHTML); of the above now looks like this:

<div class="foo">
  <p id="bar">Paragraph Text</p>
</div>

But the best part of Template String comes here: It is possible to use variables within a String without concatenation. Concatenation is now a thing of the past. It is possible to escape a Template String through ${}.

This is how concatenation was necessary to integrate a variable into a String before ES6:

let sVariable = "Paragraph Text";

let sHTML = '<div class="foo"><p id="bar">' + sVariable + '</p></div>';

And this is how to integrate a variable in a String by a Template String in ES6:

let sVariable = "Paragraph Text";

let sHTML = `
  <div class="foo">
    <p id="bar"> 
      ${sVariable} 
    </p>
  </div>
`;

So, by a Template String it is not only possible to write in JavaScript and output a String beautiful with line breaks and white spaces. But also to use variables within a String without the need of concatenation.

Most Recent Articles

Will SAP UI5 replace the SAP Web UI?

SAP Full Forms

More Similar Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu