Show the Local Weather - using switch statements for icons?

Show the Local Weather - using switch statements for icons?
0.0 0

#1

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.


#2

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


#3

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.


#4

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


#5

I have always understood the opposite, especially when if there are a large number of comparisons to be made. It really depends on the JavaScript engine of the browser, which will be more efficient (i.e. faster).

Assuming each weather condition has an icon associated with it, a more efficient solution would be to use a lookup table such as below. The icons shown below are made up and do not belong to a particular icon library. I am merely using something which resembles you original code to show how it could be used.

var conditionIcons = {
  Clear: "wi wi-clear",
  Cloudy: "wi wi-cloud"
  Sunny: "wi wi-sun"
}

Then, to add the icon to the div with id=“current-weather”, you would write:

$("#current-weather").html("<i class='" + conditionIcons[json.weather[0].main] + "'> </i>");