+ 1
How to shorten this code
How to make this code shorter with Switch statement or Tenary operators let RoomTemp = 40; const Hot = 100; const cold = 0; const warm = 40; if (RoomTemp >= Hot){ console.log("Too hot!"); } else if (RoomTemp == warm) console.log("Best Temperature"); else if (RoomTemp <= cold) console.log("Too cold!"); else console.log("Normal temperature");
9 ответов
+ 4
this?
let RoomTemp = 40;
const HOT = 100;
const COLD = 0;
const WARM = 40;
console.log(
RoomTemp>=HOT ? "Too hot!" :
RoomTemp<=COLD ? "Too cold!" :
RoomTemp==WARM ? "Best temperature" :
"Normal temperature");
+ 2
It won't get any simpler than it already is. Sure you can use ternary but it'll just reduce the readability & switch statement is not suitable for such cases
+ 2
Try this:
let RoomTemp = 40;
const Hot = 100;
const cold = 0;
const warm = 40;
let message = RoomTemp >= Hot ? "Too hot!" : RoomTemp === warm ? "Best Temperature" : RoomTemp <= cold ? "Too cold!" : "Normal temperature";
console.log(message);
+ 1
Bob_Li
Thanks🎯
+ 1
U can use it but i dont think it makes the code shorter hh
let RoomTemp = 40;
const Hot = 100;
const cold = 0;
const warm = 40;
switch (true) {
case RoomTemp >= Hot:
console.log("Too hot!");
break;
case RoomTemp === warm:
console.log("Best Temperature");
break;
case RoomTemp <= cold:
console.log("Too cold!");
break;
default:
console.log("Normal temperature");
break;
}
0
zexu knub thanks man, I just started Tenary and I just thought of trying it to see how it'll look like with ternary 🤝🏽
0
Use switch statement its a lot easier
0
Youcef Baha
How? Doesn't seem possible
0
Youcef Baha
😅Yeahh it's still close to the same length as using if statements
. But thanks tho 😊