+ 1

Switch - Or logical operator only works one way? Why?

I'm using an or logical operator in a switch, but it only works one way; box.min==0||1 works, but box.min==1||0 doesn't work and I'm unsure as to why. It doesn't appear to inhibit my desired process in any way, but I would like to isolate the issue and understand why JS behaves the way it does. EXTRA INFO: I'm fairly new to JS (and any other language for that matter-- besides prior dabbling in c++ years ago) so I'm making this tiny project so that I can use the knowledge I've acquired in an interesting way. https://code.sololearn.com/WmKnO5g3LX5U/?ref=app

3rd May 2020, 2:13 AM
EpoDogma
EpoDogma - avatar
4 Réponses
+ 2
Hello there EpoDogma, this is a quite interesting question and I had a good time to figure out what's exactly happening :)) Let's console log the condition in the 'default' case. Like so : default: console.log(box.min == 1||0) console.log(box.min == 0||1) As the first, result you'd get is '0'. And the second one you'd get 'true'. Quite amazing right? Let us break it down : Case - 1 : 'box.min == 1||0' giving us the result zero, because 'box.min == 1' returns false. As it is false 'or' operator avoid this condition and gives us '0'. And in JavaScript '0' is by default false. console.log(Boolean(0)); // false That is why the overall condition or box.min == 1||0 becomes false and 'case 1' doesn’t get run. So obviously it runs what's inside the deafult case :)) Case - 2 : box.min == 0||1 is 'true'. Because in your code 'box.min == 0' returns true and that is why it doesn’t consider any further condition and go forward. So 'box.min == 0||1' just works fine and the 'case 1' runs as well.
3rd May 2020, 2:56 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 2
[...continued] To check 'box.min == 1' is false and 'box.min == 0' is true, you can also console log them like so :)) default : console.log(box.min == 1); // false console.log(box.min == 0); // true Hope the answer helps :))
3rd May 2020, 3:01 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 2
You are most welcome :)) I think you are a bit wrong there. Instead of using : switch(box.min == 0||1) { .... } This should be used : switch(box.min) { ... } And feel free to ask any question. I'll try my best to answer :))
3rd May 2020, 3:39 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 1
Hello Arb Rahim Badsa, thank you for your guidance! It was very helpful and also quite insightful! Is there any way to prevent JS from reading the numbers as boolean values? EDIT: Also, if you run the program you may notice that the yellow square identified as "box2" moves rapidly within the "box" entity. However, whenever "box" is moving left "box2" appears to lose it's momentum and only moves proportionally with "box". Why doesn't "box2" continue moving at an accelerated pace within "box"?
3rd May 2020, 3:35 AM
EpoDogma
EpoDogma - avatar