Weather App - Question on If Else vs Switch

Hi dear campers,

I’ve just finished my weather app, which you can see[ here].

However, in a previous draft, I encountered a problem that I couldn’t figure out for the life of me. I was trying to change the background image using the “if … else” statements. However, the change worked on some weather conditions - such as “clear-day”, “fog”, but for the rest, including “rain”, “snow” etc. they all started showing the image that I set for the "“cloudy”||“partly-cloudy-day” condition. It is noteworthy that all those conditions that weren’t working was set behind the “cloudy”/"partly-cloudy-day conditions.

I therefore “switched” to the “switch” statement, and it all worked. However, I would really appreciate it if someone could explain why the “if … else” function didn’t work at the first place.

The code is below. And you can see the draft project here. Thanks in advance!

if(newWeather === “fog”)
$(‘body’).css(“background-image”, ‘url(“”)’);}
else if(newWeather === “clear-day”){
$(‘body’).css(“background-image”, ‘url(“”)’);}

 else if(newWeather === "cloudy"||"partly-cloudy-day")
 $('body').css("background-image", 'url("")');}
 else if(newWeather === "clear-night"||"partly-cloudly-night")
    $('body').css("background-image", 'url("")');}
 else if(newWeather === "rain")
    $('body').css("background-image", 'url("")');}
 else if(newWeather === "snow"||"sleet")
    $('body').css("background-image", 'url("")');}
 else if(newWeather === "wind")
    $('body').css("background-image", 'url("")');};

I think the errors are in these parts:

Maybe you meant (newWeather === 'snow') || (newWeather === 'sleet').

In your current code 'snow' || 'sleet' will always evaluate to 'snow'.

1 Like

slightly off-topic: I think you can use objects as an alternative to if-else and switch.

var icons = {
  'clear-day': '',
  'clear-night': '',
  // ...

$('img').attr('src', icons[newWeather]);

// same with the backgrounds

Hi thank you so much! I changed the first wrong OR condition (newWeather === "“cloudy”||“partly-cloudy-day”) to the correct statement as you suggested, and the rest of the conditional background change all worked!

Now I know newWeather === “cloudy”||“partly-cloudy-day” will always evaluate to True … Also found a related StackOverflow post here – "Yes, I discovered the hard way that you have to include each statement separately. I worked out that if (number === 1||2||3) is like while (true); the second and third conditions ask if 2 is 2 and/or 3 is 3. They always resolve as true to the statement always passes. "

ah I see what you did here. A much more efficient way indeed. Thanks a lot for the suggestion. Really appreciate it.