settingsAccountsettings
Menusettings

Q: Day of the Week - JavaScript task

+5 votes

Write a JavaScript function that prints a number between 1 and 7 when a day of the week is passed to it as a string and an error message if the string is not recognized. The input comes as a single string argument.

Examples:

Input: Monday
Output: 1


Input: Friday

Output: 5


Input: Frabjoyousday

Output: error

The output should be returned as a result of your program.

asked in JavaScript category by user hues

2 Answers

+4 votes

My days of the week :-)

function dayOfWeek(day) {
    if (day == "Monday") {
        return 1;
    }
    if (day == "Tuesday") {
        return 2;
    }
    if (day == "Wednesday") {
        return 3;
    }
    if (day == "Thursday") {
        return 4;
    }
    if (day == "Friday") {
        return 5;
    }
    if (day == "Saturday") {
        return 6;
    }
    if (day == "Sunday") {
        return 7;
    }
    else {
        return "error";
    }
}
console.log(dayOfWeek("Sunday"));
answered by user icabe
+2 votes

@icabe, it is easier to use switch case to solve the code:

function checkDay(input) {
    switch (input) {
        case "Monday":
            return 1;
        case "Tuesday":
            return 2;
        case "Wednesday":
            return 3;
        case "Thursday":
            return 4;
        case "Friday":
            return 5;
        case "Saturday":
            return 6;
        case "Sunday":
            return 7;
            break;
        default:
            return "error";
            break;
    }
}

console.log(checkDay("Tuesday"));

 

answered by user john7
...