DEV Community

Star
Star

Posted on

Create Strings using Template Literals

Create Strings using Template Literals

Apparently a special type of string exists, a Template Literal, a feature of ES6. “Template literals allow you to create multi-line strings and to use string interpolation features to create strings.” I’m not sure wtf this means.
Interpolation
Definition:

  1. the act or process of interpolating or the state of being interpolated.
  2. something interpolated, as a passage introduced into a text.

Prompt

I don’t know who wrote this, but holy shit.
“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).”

[
  '<li class="text-warning">no-var</li>',
  '<li class="text-warning">var-on-top</li>',
  '<li class="text-warning">linebreak</li>'
]
Enter fullscreen mode Exit fullscreen mode
const result = {

  success: ["max-length", "no-amd", "prefer-arrow-functions"],

  failure: ["no-var", "var-on-top", "linebreak"],

  skipped: ["no-extra-semi", "no-dup-keys"]

};

function makeList(arr) {

  // Only change code below this line

  const failureItems = [];

  for (let i=0; i < arr.length; i++) {

    failureItems.push(`<li class="text-warning">${arr[i]}</li>`);
  } 
  // Only change code above this line

  return failureItems;

}
const failuresList = makeList(result.failure);
Enter fullscreen mode Exit fullscreen mode
  • Iiterate as long as i = 0 is less than the length of the array
  • Any failed items with the List element with the "text-warning" class will be pushed into the currently empty array, failureItems.
  • Instead of using concatenation, we're using the Template Literal ${variable} within the failureItems.push(argument) in conjunction with the list class element in order to accept any array found within any list elements with a class of 'text-warning'.
  • When failuresList executes, it prompts the function makeList to propogate the failure results which are produced from the function makeList(arr). 
  • makeList(arr) uses the const failureItems which is an empty array until the for loop is executed, which is nearly at the same time(thanks computers).

Error: 

"failuresList should be equal to the specified output. Template strings and expression interpolation should be used."

The problem was me using quotes instead of backticks. FFS.

Top comments (0)