68
devios1
7y

I just encountered this:

switch (boolean) {
case true:

break;
case false:

break;
}

Comments
  • 7
    That's horrible even in JS standards 😂
  • 4
    If the Boolean can be null I can understand it.
  • 7
    @bkwilliams It actually can't be; I omitted it for brevity but it's actually doing a !! on the parameter, meaning it's always going to be either true or false. :P
  • 2
    Then it might be a hardware thing. The true block of an “if” is put into the CPU pipeline to be worked before the result of the “if” condition is known. When the condition is false, whatever is in the pipeline is thrown away and the false block is loaded. “Switch/Case” does not follow that convention.

    But that was a while ago and hardware may have changed.
  • 0
    Well this isnt to bad?
    In some languages a boolean can be undefined or null.
  • 2
    @bkwilliams Doesn't that just apply to compiled code? The only branch prediction that would be happening would be in the js interpreter, wouldn't it?

    Then again I don't know what kind of optimizations the interpreter does behind the scenes. It could actually JIT compile it for all I know.

    Regardless, judging by the numerous other atrocities in this code I assure you the reasons for doing this are not optimization. :P
  • 2
    @valvy It's bad for a number of reasons. Logically it's fine, we all know it'll execute fine, but the problem is in communication of intent, readability, chance for mistakes, etc.

    Logically this is a simple boolean condition. As I mentioned above, though I omitted it from the snippet, boolean is actually boolean: it's either true or false.

    I also didn't mention that the cut out code is actually almost 200 lines of code. So this isn't even concisely viewable in a single page of code. It's two giant case statements inside what could have been a simple if/else.
  • 5
    Just in case Boolean gets more values, always think about the future...always! 😛
  • 1
    @gitpush
    if (condition === maybe) { ... }
  • 3
    I think he just learnt switch case and wanna try how it works
Add Comment