const number = prompt("Enter your number");
const txt = "You result is : ";
switch (number) {
case (number >= 80 && number <= 100):
document.write(`${txt} A `);
break;
case (number >= 70 && number <= 80):
document.write(`${txt} A gread`);
break;
case (number >= 60 && number <= 70):
document.write(`${txt} B gread`);
break;
case (number >= 50 && number <= 60):
document.write(`${txt} C gread`);
break;
case (number >= 33 && number <= 50):
document.write(`${txt} D gread`);
break;
case (number >= 0 && number <= 33):
document.write(`${txt} Field !`);
break;
case (number > 100 || number < 0):
document.write(`It's not a valid number. Please input any valid number.`);
break;
default:
document.write(`Not input any number. Please input any number .`);
break;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
With a switch-statement, you evaluate the expression right after switch. In your case that would be number.
So, your cases are evaluated with the number. This is what will happen:
- Suppose, we enter '88' in the prompt.
- The first thing you are evaluating
numberagainst is(number >= 80 && number <= 100). The result of the latter istrue. - now the value of
number,88is compared totrue, like this:88===true. - this results in a
false, so the next case is evaluated. - the same happens for the following cases, right until the point you hit the default-case.
CodePudding user response:
There are two reasons why this code will not work:
The first reason is because the
promptmethod return a string as you can see by typingconsole.log('Type of number:', typeof number); // Expected output: Type of number: stringYou can resolve this by parsing the output of the prompt method as follows
const number = parseInt(prompt("Enter your number"));The second reason is because in a
switchstatement statement, the evaluated value of the switch expression is compared the the evaluated values of the cases.It means that the value of
number(number) is compared to the expression(number >= 80 && number <= 100)(comparison expression) and so on with the others.So unless one of yoru case expression yield a number the
switchwill try to evaluate the value ofnumberto the expression (which is always true) meaning that theswitchis comparing45 === true, not matching any of the cases.
Just use if/else instead:
if (number >= 80 && number <= 100)
document.write(`${txt} A `);
else if (number >= 70 && number <= 80)
document.write(`${txt} A gread`);
else if (number >= 60 && number <= 70)
document.write(`${txt} B gread`);
else if (number >= 50 && number <= 60)
document.write(`${txt} C gread`);
else if (number >= 33 && number <= 50)
document.write(`${txt} D gread`);
else if (number >= 0 && number <= 33)
document.write(`${txt} Field !`);
else if (number > 100 || number < 0)
document.write(`It's not a valid number. Please input any valid number.`);
else
document.write(`Not input any number. Please input any number .`);
