Show the Local Weather - using switch statements for icons?

Right now I’m working through the “Show the Local Weather” Intermediate Front End Project, and I’m using a series of if statements based on text from the FCC Weather API. Here’s a code snippet:

if (json.weather[0].main == "Clear"){
      $("#current-weather").html("<i class=\"wi wi-cloud\"> </i>");
    }

It works fine, and I’m currently using a chain of if else statements like the one above to go through the data from the API and show a weather icon based on the “main” property (weather icons are from weathericons.io).

But I’m thinking about using a switch statement using the API’s weather “id” value to determine the case. This means that I can be a lot more specific about which icon is used, and of course it’ll make the code a lot more readable.

Switch statements are things that I’ve only ever come across in tutorials but I’ve never really seen them in actual code written by real people.

I’d like to know if this is an appropriate time to use a switch statement, or if I’m just over engineering my coding solution. Please let me know what you think. I’m trying to pick up good coding practice.

Switch statements are good if you are conditionally testing a single variable. Here’s the MDN docs (an invaluable resource) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

in your case, it would be good to use it because of one variable json.weather[0].main

1 Like

Thanks for the reply. From what I understand, they are not as computationally efficient as a series of if / else statements, but they are a lot more human readable.

I’ll implement them into my project then. I’m still very new to coding, so I was just curious about if this was a good coding solution.

i’m not sure of the difference, but there is no concern about it. they’re almost the same in terms of efficiency. especially if you order the cases in terms of frequency. the switch statement will be more readable as well

but if you have only a few cases, if/else can be just a wee bit faster. almost negligible