jeff64 jeff64 - 3 months ago 12
Javascript Question

Converting if statement to switch

I was trying to figure out if this "if" statement was possible to change to a switch statement. The code works fine it just seems like it would probably more clean the other way. The statement is for putting a certain weather image depending on the weather description that day.

Any answers are appreciated! I know this isn't very high in terms of important questions but I would like to be able to use switch statements more fluently.

if(weather === "clear sky") {
$(".weather-img").attr("src", clear);
}
else if(weather === "few clouds" || weather === " scattered clouds" || weather === "broken clouds") {
$(".weather-img").attr("src", cloudy);
}
else if(weather === "shower rain" || weather === "rain") {
$(".weather-img").attr("src", rain);
}
else if(weather === "thunderstorm") {
$(".weather-img").attr("src", thunderstorm);
}
else if(weather === "mist") {
$(".weather-img").attr("src", mist);
}
else {
$(".weather-img").attr("src", snow);
};

Answer

You can use multiple cases without a break to simulate or and default for default action. It could look like this:

switch(weather) {
  case "clear sky":
    $(".weather-img").attr("src", clear);
    break;
  case "few clouds":
  case "scattered clouds":
  case "broken clouds":
    $(".weather-img").attr("src", cloudy);
    break;
  ...
  default:
    $(".weather-img").attr("src", snow);
}