Reputation: 1
I have been messing with this for awhile now and i cant seem to figure out why the else statement does not show up when i type any negative number into the prompt box, i have tried to create an additional if statement using Math.sign(num) to check if the number is negative to check if its less than zero but i havent had any luck making it work. my thought was to rule out other possibilities and if all the above statements were false the number had to be negative. What am i doing wrong here?
var num = parseFloat(prompt("please enter a number", ""));
var barRepeat = "*".repeat(num); //made this to get a visual bar displaying * equal to the number given
if (num > 0) {
document.write(num);
document.write("=>");
document.write(barRepeat);
} else if (num == 0) {
document.write("The number you entered is 0");
} else if (isNaN(num)) {
document.write("error you entered an invalid character");
} else {
document.write("the number you entered is negative, please try again");
}
Upvotes: 0
Views: 78
Reputation: 780663
If you enter a negative number, "*".repeat(num)
gets an error and the script stops there, without ever going to the if
statements.
Move that into the if
statement so you only create the repeat bar when the input is valid.
var num = parseFloat(prompt("please enter a number", ""));
if (num > 0) {
var barRepeat = "*".repeat(num); //made this to get a visual bar displaying * equal to the number given
document.write(num);
document.write("=>");
document.write(barRepeat);
} else if (num == 0) {
document.write("The number you entered is 0");
} else if (isNaN(num)) {
document.write("error you entered an invalid character");
} else {
document.write("the number you entered is negative, please try again");
}
Whenever a JavaScript function doesn't behave as you expect, the first place you should look is the console for error messages.
Also, see Why is document.write considered a "bad practice"?
Upvotes: 1