✅ – ✅ – dmikester1 – 03-34 May 5

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;
}
N
NishantJoshi349d ago
can you show the error
D
dmikester1349d ago
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'
N
NishantJoshi349d ago
instead try doing this with if else statement, instead of switch case. Above is also the reason why only default case is running.
D
dmikester1349d ago
what is the reason why only default case is running?
N
NishantJoshi349d ago
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; }
N
NishantJoshi349d ago
Stack Overflow
JavaScript: using a condition in switch case
How can I use a condition inside a switch statement for JavaScript? In the example below, a case should match when the variable liCount is <= 5 and > 0; however, my code does not work: switch (
N
NishantJoshi349d ago
check this out... you will understand the concept, and why your code was not working
S
ScriptyChris349d ago
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
UU
Unknown User347d ago