0

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.

1
  • 1
    Define "doesn't work". Commented Mar 15, 2016 at 11:27

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 */
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.