5 Neat JavaScript tricks for better programming.
1. Clearing or truncating an array - Change the length property.
const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> ...
hashnode.com
That "trick" of "switch(true)" is one of the most wasteful from a processing and memory standpoint there is. It entirely defeats the purpose of using switch (setting the value to compare against once) and results in doing MORE comparisons than necessary as you have a literal "true ===" instead of a soft conditional.
That is most certainly a case where if/else would be more efficient -- and really no more or less code.
Pretty much if you don't put the variable into your SWITCH, you're completely defeating the point of using it instead of if/else.
The example also has a wasted less than. It already tested for <=0 so why would you need to test for >0 afterwards? The "variable for nothing" isn't helping matters either...
Why would anyone use that instead of:
function getWaterState(tempInCelsius) { if (tempInCelsius <= 0) return 'Solid'; if (tempInCelsius < 100) return 'Liquid'; return 'Gas'; }Or even better, go ternary given what's being done.
function getWaterState(tempInCelsius) { return tempInCelsius <= 0 ? 'Solid' : ( tempInCelsius < 100 ? 'Liquid' : 'Gas' ); }The whole point of switch/case is the efficiency of using a variable on the switch against a single value on the case, playing directly to how at the machine language level the various "Jxx" commands such as JZ (jump on zero), JC (jump on carry), JS (jump on sign) after a CMP (compare), ADD, SUB, or any other operation that sets the flags. This is particularly true of operations that can be fit into a single register (like integers) though string comparisons can 'short circuit' on mismatch using (on x86/x64) REP CMPSB (if the lengths are known, gets more complex when they aren't -- another of the many reasons not to use null terminated strings no matter how much C loves them!).
Using it with a static value on the switch is just introducing extra overhead and processing time for zero real improvement in code clarity and certainly doesn't result in writing less code. I don't know who started telling people to use that technique as I've been seeing it for over a decade now, but they really needed to learn more about how things work at the low level before telling others how to code. Sadly like a great many coding practices (good or bad) one person shows it as a method, the majority just blindly parrots and copies it.
The title for #3 is also wrong, is it not? Shouldn't it be "not having a constructor or methods"?