Create Strings using Template Literals - Unexpected undefined variable

Create Strings using Template Literals - Unexpected undefined variable
0.0 0


const result = {
  success: ["max-length", "no-amd", "prefer-arrow-functions"],
  failure: ["no-var", "var-on-top", "linebreak"],
  skipped: ["id-blacklist", "no-dup-keys"]
function makeList(arr) {
  "use strict";
  const resultDisplayArray = [];
  var fail;
  const error = `<li class="text-warning">${fail}</li>`;
  for(let i=0;i<arr.length;i++){
    fail = arr[i];
  return resultDisplayArray;

const resultDisplayArray = makeList(result.failure);

In console.log(fail), I get the correct values, but in console.log(resultDisplayArray), fail appears as undefined. What am I missing?


When you create the string template, fail is undefined. It doesn’t get redefined and reinserted each time you change fail. Yes, that is something we might expect a template to do, but these don’t.

Try this:

  for(let i=0;i<arr.length;i++){
    const error = `<li class="text-warning">${arr[i]}</li>`;

That way that value is defined when each of those template literals is created. You don’t even need the variable fail. And even those two lines could be shortened into one.


I ended up using map but thanks for the clarification.