Home > front end >  How to solve Error with switch Function - JavaScript
How to solve Error with switch Function - JavaScript

Time:10-11

I am trying to create a function that gives me the month depending on the console.log info.

    function daysInMonth(month) {
  switch (month) {
    case '1': case '3': case '5': case '7': case '8': case '10': case '12':
      return '31';
    case '2':
      return '28';
    case '4': case '6': case '9': case '11':
      return '30';
    default:
      return 'You have to put a month from 1 to 12';
  }
}
var result = daysInMonth('1');
var result = daysInMonth('6');
var result = daysInMonth('2');

I am given some errors:

Log 31 30 28 function daysInMonth (month) function daysInMonth should be declared should return 31 when month is one of the following values: 1,3,5,7,8,10,12 function should return 31 when month is one of the following 1, 3, 5, 7, 8, 10, 12 : expected 'You have to put a month from 1 to 12' to equal 31 Completed in 2ms should return 30 when month is one of the following values: 4, 6, 9, 11 function should return 30 when month is one of the following 4, 6, 9, 11 : expected 'You have to put a month from 1 to 12' to equal 30 should return 28 when month is 2 function should return 28 when month is 2 : expected 'You have to put a month from 1 to 12' to equal 28

This is what I was asked to do:

Implement the logic of the function named daysInMonth. The function receives one argument month, which is an integer (whole number) in the range from 1 to 12.

It should return a number of days depending on the month of the year, as per the given table:

----------------- ------------ | month | days | ----------------- ------------ | 1,3,5,7,8,10,12 | 31 | ----------------- ------------ | 4,6,9,11 | 30 | ----------------- ------------ | 2 | 28 | ----------------- ------------ Important: You must use the keyword return to return the value from the function. Tests can only check the output value that your function returns. Any console.log output will be ignored.

I made the changes with the return, as I was assuming I had to console.log everything. Still, errors occur. Can you please help?

Thanks!

CodePudding user response:

If your tests are expecting the function to return something, your function should return the value instead of sending it to console.log.

function daysInMonth(month) {
  switch (month) {
    case '1': case '3': case '5': case '7': case '8': case '10': case '12':
      return '31';
    case '2':
      return '28';
    case '4': case '6': case '9': case '11':
      return '30';
    default:
      return 'You have to put a month from 1 to 12';
  }
}
var result = daysInMonth('2');
console.log(result === '28');
console.assert(result === '28', 'Expected days in month 2 to equal 28');

CodePudding user response:

I was defining a string when I was supposed to define cases as integers. Re-read the request and got to that conclusion.

  • Related