Home > Blockchain >  Try to write a function that returns the day of the week when called
Try to write a function that returns the day of the week when called

Time:08-02

Write a function called returnDay. this function takes in one parameter (a number from 1-7) and returns the day of the week (1 is Monday, 2 is Tuesday, etc.) If the number is less than 1 or greater than 7, the function should return null. In some countries Sunday is treated as the first day of the week, but for this exercise we will use Monday as the first day.

My Code:

function returnDay(num) {
    const daysOfWeek = {
       1: "Monday",
       2: "Tuesday",
       3: "Wednesday",
       4: "Thursday",
       5: "Friday",
       6: "Saturday",
       7: "Sunday",
    };
    if (num < 1 && num > 7) {
        return null;
    } else {
        return num;
    }
}

CodePudding user response:

Well, you did just right, the only thing as was already mentioned in the comments: num can't be both less than 1 and more than 7, you need to use OR operator. But you already have numbers of the days in the object, why not opt for a simple ternary operator if you need to return null specifically:

return daysOfWeek[num] ? daysOfWeek[num] : null

CodePudding user response:

You want a switch statement. This page has your answer almost exactly, but to wrap it in a function you can remove the breaks.

function returnDay(num) {
switch (num) {
    case 1:
      return 'Sunday';
    case 2:
      return 'Monday';
    case 3:
      return 'Tuesday';
    case 4:
      return 'Wednesday';
    case 5:
      return 'Thursday';
    case 6:
      return 'Friday';
    case 7:
      return 'Saturday';
    default:
      return 'Invalid day';
  }
}

This starts at Sunday, so just reshuffle them.

  • Related