+ 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");

14th Jul 2023, 10:13 PM
Madu Victor
Madu Victor - avatar
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");
15th Jul 2023, 1:02 AM
Bob_Li
Bob_Li - avatar
+ 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
15th Jul 2023, 12:06 AM
zexu knub
zexu knub - avatar
+ 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);
16th Jul 2023, 7:40 PM
Kevin Kraaijveld
Kevin Kraaijveld - avatar
+ 1
Bob_Li Thanks🎯
15th Jul 2023, 9:17 PM
Madu Victor
Madu Victor - avatar
+ 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; }
19th Jul 2023, 8:03 PM
Youcef Baha
Youcef Baha - avatar
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 🤝🏽
15th Jul 2023, 9:13 PM
Madu Victor
Madu Victor - avatar
0
Use switch statement its a lot easier
16th Jul 2023, 8:20 PM
Youcef Baha
Youcef Baha - avatar
0
Youcef Baha How? Doesn't seem possible
19th Jul 2023, 7:50 PM
Madu Victor
Madu Victor - avatar
0
Youcef Baha 😅Yeahh it's still close to the same length as using if statements . But thanks tho 😊
19th Jul 2023, 9:10 PM
Madu Victor
Madu Victor - avatar