Js function if/else into switch

Hi in the exercise about function expression i need to make this code :

const plantNeedsWater = function(day){
  if (day==='Wednesday'){
  return true;}

  else{
    return false;
  }
};
console.log(plantNeedsWater('Wednesday'));

it worked, but I want to try to make the same with a Switch and can’t get my head around it ^^ I get an undefined log.

my code :

const plantNeedsWater = function (day) {
    switch (day) {
        case day === 'Wednesday': return true;
           
    }
};

console.log(plantNeedsWater('Wednesday'));

Hope my English is understandable as it’s not my main language :wink:

exercise link : https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-functions/lessons/functions/exercises/function-expressions

using a switch statement means the comparison is done for you, so the case should be case 'Wednesday', and for else you could use default

1 Like

Oh ! thank you … feel dumb ahah

let plantNeedsWater = function (day) {
    switch (day) {
        case 'Wednesday' : return  true;
        default : return false;    
    }
    
};
console.log(plantNeedsWater('tuesday'));

working now (here with a false result)

using switch for a single case is not common practice

personally, i even find using if/else here tedious. You could shorten this using ternary operator:

return day === 'Wednesday' ? true : false;

which is a shorthand for if/else. But this could be written even shorter:

return day === 'Wednesday'

given a comparison result in a Boolean value.

1 Like

yes, I understand that there is no need here for a switch with a single case, just try to always test a different way :sweat_smile:
thank you for the ternary operator, I need to master that also ^^.

let plantNeedsWater = function (day) {
    return day === 'Wednesday';
    };
console.log(plantNeedsWater('Wednesday'));

:ok_hand: :+1:

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.