Create Strings using Template Literals

A new feature of ES6 is the template literal. This is a special type of string that makes creating complex strings easier.

Template literals allow you to create multi-line strings and to use string interpolation features to create strings.

  • Let's consider the code below
const person = {
  name: "Randy Rivera",
  age: 24

const greeting = `Hello, my name is ${}!
I am ${person.age} years old.`;
  • The console will display the strings Hello, my name is Randy Rivera! I am 24 years old.

To be honest with you a lot happed in this code. First, the example uses backticks (`), not quotes (' or "), to wrap the string. Second, notice that the string is multi-line, both in the code and the output. This saves inserting \n within strings. The ${variable} syntax used above is a placeholder. Which is basically, you won't have to use concatenation with the + operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with ${ }.

  • Let's Challenge ourselves:

Use template literal syntax with backticks to create an array of list element (li) strings. Each list element's text should be one of the array elements from the failure property on the result object and have a class attribute with the value text-warning. The makeList function should return the array of list item strings. Use an iterator method (any kind of loop) to get the desired output(shown below, for this example let's go with this).

  '<li class="text-warning">no-var</li>',
  '<li class="text-warning">var-on-top</li>',
  '<li class="text-warning">linebreak</li>'

const result = {
 success: ["max-length", "no-amd", "prefer-arrow- 
 failure: ["no-var", "var-on-top", "linebreak"],
 skipped: ["no-extra-semi", "no-dup-keys"]

function makeList(arr) {
  const failureItems = [];
  for (let i = 0; i < arr.length; i++) {
    failureItems.push('<li class="text-warning">${arr[i]}</li>')

  return failureItems;

const failuresList = makeList(result.failure);

console.log(failuresList); will display 
[ '<li class="text-warning">no-var</li>',
  '<li class="text-warning">var-on-top</li>',
  '<li class="text-warning">linebreak</li>' ]