R
Reactiflux

help-js

✅ – ✅ – dmikester1 – 03-34 May 5

Ddmikester15/5/2023
What am I doing wrong here? tempRating is always 'hot'
const temp = 10; //r.data.weatherData.temp;
console.log({ temp });
switch (temp) {
case temp <= 30:
setTempRating('cold');
break;
case temp <= 50:
setTempRating('cool');
break;
case temp <= 70:
setTempRating('warm');
break;
default:
setTempRating('hot');
break;
}
const temp = 10; //r.data.weatherData.temp;
console.log({ temp });
switch (temp) {
case temp <= 30:
setTempRating('cold');
break;
case temp <= 50:
setTempRating('cool');
break;
case temp <= 70:
setTempRating('warm');
break;
default:
setTempRating('hot');
break;
}
NNishantJoshi5/5/2023
can you show the error
Ddmikester15/5/2023
there is no error, tempRating gets set to 'hot' on every run based on a 'temp' value of 10, it should be getting set to 'cold'
NNishantJoshi5/5/2023
instead try doing this with if else statement, instead of switch case. Above is also the reason why only default case is running.
Ddmikester15/5/2023
what is the reason why only default case is running?
NNishantJoshi5/5/2023
well if you want to run it do one thing do switch(true){ // your code } const temp = 10; function setTempRating(val) { console.log(temp is ${val}); } switch (true) { case temp <= 30: setTempRating("cold"); // console.log("first" + temp); break; case temp <= 50: setTempRating("cool"); // console.log("second" + temp); break; case temp <= 70: setTempRating("warm"); // console.log("third" + temp); break; default: setTempRating("hot"); break; } https://stackoverflow.com/questions/5464362/javascript-using-a-condition-in-switch-case check this out... you will understand the concept, and why your code was not working
SScriptyChris5/5/2023
The reason why default case is always executed is because temp is compared to each case expression, e.g. temp === (temp <= 10) - > temp === true -> false. Every case condition is evaluated first (returning true, cause 10 is less than every number compared in there) and then 10 is compared to true, which gives false, so default is matched
UUUnknown User5/7/2023
4 Messages Not Public
Sign In & Join Server To View

Looking for more? Join the community!