Hi everyone. I’m going through Beginning Javascript 5th edition as I go through FreeCodeCamp, and I’ve encountered an issue. The exercise says to write a function which displays the times tables (1-12) requesting the times table from the user, checking if it’s a valid number, and stopping when the user enters -1. I couldn’t do this by myself without peeking at the answers, so I’m even more surprised by the fact that this happens. I’ve checked the answers, and with the exception of variable names, it’s pretty much identical. Everything seems to work fine except this is what happens when you run it:
- you get a promp window requesting a number between 1-12, which also has a placeholder value (-1). You type a valid number, say 5, and press enter.
**- Nothing happens and you get the same prompt window again, with the same placeholder value (-1). Here you have to press enter again in order for it to actually print the desired results to the html (in this case, the 5 times table). **
What seems to happen is that it only stops going through the loop and executing the document.write line after the user has entered -1. What it should do is request and display the results for each value, which it doesn’t until the user enters -1. i What the hell is going on? Bear in mind I’m a newbie so sorry if this is a very stupid question. Here’s my code:
<script>
function multiply (timesTable, startValue, endValue) {
for (; startValue <= endValue; startValue++){
document.write(timesTable * startValue + "<br />");
}
}
var timesTable;
while((timesTable = prompt("Enter a number from 1 to 12.", -1)) != -1) {
while(isNaN(timesTable) == true) {
timesTable = prompt("Enter a valid number", -1);
}
if (timesTable == -1){
break;
}
document.write("The " + timesTable + " times table" + "<br />");
multiply(timesTable, 1, 12);
}
</script>