Convert the following JavaScript code by replacing the switch
statement with an equivalent (nested) if-statement :
Month = today.getMonth();
switch (Month)
{
case 0:
case 1:
case 11:
season = "winter";
break;
case 2:
case 3:
case 4:
season = "spring";
break;
case 5:
case 6:
case 7:
season = "summer";
break;
default:
season = "fall";
}
Description:
In the switch statement if 'Month' value is 0 or 'Month' value is 1 or 'Month' value is 11, the statement season =Winter; will be executed. (We can write it as if(Month==0||Month==1||Month==11) { season = "winter"; } ).
We can represent remaining two (cases 2,3,4 and cases 5,6,7) as above.
The last case (default case) is executed if all the above statements are not true.
Answer:
Month = today.getMonth();
if(Month==0||Month==1||Month==11)
{
season = "winter";
}
else if(Month==2||Month==3||Month==4)
{
season = "spring";
}
else if(Month==5||Month==6||Month==7)
{
season = "summer";
}
else
{
season = "fall";
}
Get Answers For Free
Most questions answered within 1 hours.