Im trying to create a string output using numbers. User enters a number + corresponding string is output
My code seems off + also is there a way to use for/while loop to make this neater?
//Single input
let num = prompt("Please enter a number");
//Comparing if
if (num === 1)
{
console.log("Mon");
}
else if (num === 2)
{
console.log ("Tue");
}
else if (num === 3)
{
console.log ("Wedn");
}
else if (num === 4)
{
console.log ("Thurs");
}
else if (num === 5)
{
console.log ("Frid");
}
else if (num === 6)
{
console.log ("Satu");
}
else if (num === 7)
{
console.log ("Sund");
}
let num = prompt("Please enter a number");
returns a string, not a number, you'd have to convert the result to number.
One way to do it:
let num = +prompt("Please enter a number"); // note the plus sign before prompt
or
let num = parseInt(prompt("Please enter a number"));
//Single input
let num = +prompt("Please enter a number");
//Comparing if
if (num === 1)
{
console.log("Mon");
}
else if (num === 2)
{
console.log ("Tue");
}
else if (num === 3)
{
console.log ("Wedn");
}
else if (num === 4)
{
console.log ("Thurs");
}
else if (num === 5)
{
console.log ("Frid");
}
else if (num === 6)
{
console.log ("Satu");
}
else if (num === 7)
{
console.log ("Sund");
}
Regarding making this neater?
const daysOfTheWeek = ["Mon", "Tue", "Wedn", "Thurs", "Frid", "Satu", "Sund"];
const day = +prompt("Please enter a number");
if(day > 0 && day <= daysOfTheWeek.length){
console.log(daysOfTheWeek[day - 1]);
} else {
console.log("No such day");
}