skip to Main Content

Hello in this code when I am seeing the output, it is not working.

for (var i = 1; i <= 10; i++) {
   var x = '2 × ' +i +' = ' +2*i +'<br>';
};
document.getElementById('table').innerHTML = x;
<p id="table"></p>

I expected it to give the text to that paragraph.
This text: 2 × 1 = 2
And upto 2 × 10 = 20
Also there was <br> for next line.

I tried to declare x outside also but still it is not working:

The modified code inside <script>

var x;
for (var i = 1; i <= 10; i++) {
   x = '2 × ' +i +' = ' +2*i +'<br>';
};
document.getElementById('table').innerHTML = x;
<p id="table"></p>

3

Answers


  1. <p id="table"></p>
    
    <script>
      let x = '';  // set to empty space
    
      for (let i = 1; i <= 10; i++) {
        x += '2 × ' + i +' = ' + 2*i +'<br>';  // use +=
      };
    
      document.getElementById('table').innerHTML = x;
    </script>
    Login or Signup to reply.
  2. Assuming that you want to have all x values. You need to append them.

    Try this:

    var x = ''; // added a default value
    for (var i = 1; i <= 10; i++) {
       // switched to += (concatenation)
       x += '2 × ' + i +' = ' + 2*i + '<br>';
    }
    
    document.getElementById('table').innerHTML = x;
    
    Login or Signup to reply.
  3. You’re overwriting x on each iteration of the loop.

    Initialize x to an empty string, then use += to concatenate to it.

    var x = '';
    for (var i = 1; i <= 10; i++) {
       x += '2 × ' +i +' = ' +2*i +'<br>';
    };
    document.getElementById('table').innerHTML = x;
    <p id="table"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search