guillemus
guillemus

Reputation: 101

declaring variable inside while loop javascript

I don't understand this code.

var timesTable;
while ((timesTable = prompt("Enter the times table", -1)) != -1) {.....}

Why is necessary to declare the variable before? I tried to do this:

while ((var timesTable = prompt("Enter the times table", -1)) != -1) {.....}

but it doesn't work. What's the problem? Is something about scope?

The full program is:

function writeTimesTable(timesTable, timesByStart, timesByEnd) {
        for (; timesByStart <= timesByEnd; timesByStart++) {
            document.write(timesTable + " * " + timesByStart + " = " + timesByStart * timesTable + "<br />");
            }
        }
    var timesTable;
    while ((timesTable = prompt("Enter the times table", -1)) != -1) {
        while (isNaN(timesTable) == true) {
            timesTable = prompt(timesTable + " is not a " + "valid number, please retry", -1);
        }
        document.write("<br />The " + timesTable + " times table<br />");
        writeTimesTable(timesTable, 1, 12);
    }

Thanks by advance.

Upvotes: 0

Views: 4137

Answers (2)

Stephen Paul
Stephen Paul

Reputation: 39025

This is the best alternative I could come up with

for (let i = 0; i < Number.MAX_VALUE; i++) {
  const variable = getVariable(i);
  if (/* some condition */) { break; }
  /* logic for current iteration */
}

Upvotes: 0

epoch
epoch

Reputation: 16615

You can't define a variable within a while loop, there is no such construct in javascript;

enter image description here

The reason that you can define it within a for loop is because a for loop has an initialization construct defined.

for (var i = 0; i < l; i++) { ... }
//     |           |     |
// initialisation  |     |
//            condition  |
//                    execute after each loop

Basically, it won't work because it is invalid code.

You can however remove the var declaration completely, but that will essentially make the variable global and is considered bad practice.

That is the reason you are seeing the var declaration directly above the while loop

Upvotes: 7

Related Questions