1

The for loop seems to run fine but fails to update the element variable. My intention was:

<h6>Q1</h6>
<h6>Q2</h6>
<h6>Q3</h6>

Instead, the actual result was:

<h6>Q1</h6>
<h6>Q1</h6>
<h6>Q1</h6>

  function results () {

     var listResults = '';
     var i=0;
     const element = `
      <h6>Q${i+1}</h6>
     `;

     for(x=0; x < 3; x++) {
        listResults += element;
        i++;
     }
     return listResults;
    }
    console.log(results())
Dale
  • 1,901
  • 10
  • 18
user3558349
  • 15
  • 1
  • 3
  • 4
    Because at the moment the template literal is evaluated `i` has to the value `0`. If you want to get different result you have to define the template literal inside the loop. – Felix Kling Nov 03 '17 at 17:16
  • You probably want to move `const element = …` inside the for loop. – helb Nov 03 '17 at 17:17
  • 1
    https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused – epascarello Nov 03 '17 at 17:18

6 Answers6

1

A few issues. Mainly, when element is evaluated i is 0 so element always returns <h6>Q1</h6>.

You can append the template literal directly to the output like this:

function results () {

 var listResults = '';

 for(x=0; x < 3; x++) {
  listResults += `<h6>Q${x+1}</h6>\n`;
 }
 return listResults;
}
console.log(results())
Brett DeWoody
  • 55,478
  • 28
  • 131
  • 182
1

The template is evaluated as soon as the expression is parsed. Something like this could work:

let listResults = [];
const element = i => `<h6>Q${i+1}</h6>`;

for(x=0; x < 3; x++) {
    listResults += element(x);
}
ktilcu
  • 2,764
  • 1
  • 16
  • 15
0

The main issue is that element is assigned once, when i is equal to 0. It never gets updated beyond that (despite i incrementing with each loop).

Furthermore, using a more modern method like .map yields a much more readable version of your outcome:

const results = () => [1, 2, 3]
    .map(i => `
        <h6>Q${i}</h6>
    `)
    .join('');

console.log(results());
ryanpcmcquen
  • 5,857
  • 3
  • 22
  • 35
0

you have this problem only because you are declaring i variable every time you revoke function , and actually every time you are setting it to 0 and continuing . so, the "i" variable must be declared out of(and before declaring) function (not in it) and every time you invoke function, it's value will be added by one.

var i=0;
function results () {

     var listResults = '';
     const element = `
      <h6>Q${i+1}</h6>
     `;

     for(x=0; x < 3; x++) {
        listResults += element;
        i++;
     }
     return listResults;
    }
console.log(results())
Kavian Rabbani
  • 600
  • 3
  • 15
0

Some ES6:

const results = _ => Array.from({length:3}, i => `<h6>Q${i+1}</h6>`).join("\n");
Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
0

try this using eval:

var element = "<h6>Q${i}</h6>";

var results = [1, 2, 3].map(function (i) {
  return eval('`'+element+'`');
});
console.log(results);