Rookie.S
Rookie.S

Reputation: 5

Javascript counter controlled loop using (while) error

I am a newbie for java script programming. I want to print integers from 0 to 100. here is my code.

    var outputAreaRef = document.getElementById("outputArea");


var i = 0; //Initialize counter
var number = 0;
while ( i <= 100) // Test Counter
    {
      number = number + 1 + "<br />";
        i = i + 1; // Increment counter
        outputAreaRef.innerHTML = number;

    }

it prints digit 1 hundred times. but if i change the code like this, number = number + i + "; it will print from o to hundred. waht is the difference between the two codes? thanks in advance

Upvotes: 0

Views: 309

Answers (3)

hankchiutw
hankchiutw

Reputation: 1662

var number became a String after first run and digit 1 concat to number afterward.

Upvotes: 0

madox2
madox2

Reputation: 51881

You are mixing strings with numbers. You need to do numerical computation in one variable and string concatenation in another. To increment number you can re-use i variable:

var outputAreaRef = document.getElementById('outputArea');
var i = 0;
var number = '';
while (i <= 100) {
    i = i + 1; // numeric addition
    number = number + i + '<br />'; // string concatenation
}
outputAreaRef.innerHTML = number; // it is ok to set html content only once

Upvotes: 1

chris97ong
chris97ong

Reputation: 7070

The code doesn't work because your output is number, and number is never changed and will remain as 0 because in the while loop, only i is changed.

Also change :

outputAreaRef.innerHTML = number;

to

outputAreaRef.innerHTML = outputAreaRef.innerHTML + number;

so that the whole innerhtml of the output area will not be replaced every loop.


Modify your while loop and it will work perfectly:

while ( i <= 100) {
    number = i + 1 + "<br />";
    i = i + 1; // Increment counter
    outputAreaRef.innerHTML = outputAreaRef.innerHTML + number;
}

Working fiddle

Upvotes: 0

Related Questions