Weather app: Is there a more elegant way ot doing this? (going back to °C when checkbox is unchecked)

Hi everyone,
my weather app is working beautifully. I encountered the issue of having to go back to °C from °F when the user unchecks the toggle checkbox, and I solved it in a very rudimentary way, and I wonder if there is a better way to do this.

Here’s my pen:

I’d truly appreciate some feedback on this.

I think that there are only so many things you can do to make this functionality. If you want to make it more elegant, or at least look a little less un-DRY (meaning Don’t Repeat Yourself) you could pre-compute your Fahrenheit values, even storing them as strings, in a structure, perhaps an array or an object, and have two different array locations, one with C and one with F, and then just set an index to access them so that there is only one set of code to update the displayed values - maybe it would look something like this:

var temps = {
    F: {
        temp: // store the current F temp here,
        min: // store the min F temp here,
        max: // store the max F temp here
    C: {
        temp: // store the current temp here,
        min: // store the min temp here,
        max: // store the max temp here

The to access it you can just have a variable that you set to “F” or “C” and use the bracket notation to access the values like:

var use = "F";
// etc.

so you would not redo computations each time, and only have one block of code that is using the property values to access the appropriate temperature values.

You could also cache the locations that you are storing these, because jQuery lookups are complex, so doing them once and then using them repeatedly is better in the long run.

I hope that helps…

1 Like