R
Join ServerReactiflux
help-js
✅ – ✅ – 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;
}
can you show the error
there is no error,
tempRating
gets set to 'hot' on every runbased on a 'temp' value of 10, it should be getting set to 'cold'
instead try doing this with if else statement, instead of switch case. Above is also the reason why only default case is running.
what is the reason why only default case is running?
well if you want to run it do one thing
do
switch(true){
// your code
}
switch(true){
// your code
}
const temp = 10;
function setTempRating(val) {
console.log(
}
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;
}
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;
}
check this out...
you will understand the concept, and why your code was not working
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 matched3 Messages Not Public
Sign In & Join Server To View