I saw a piece of code that stuck me as odd. What does switch(!0) mean in javascript? What are some cases where this technique would be useful to use?
jsTree uses it in a few places but it looks foreign. I'm sure it has a good reason behind it, but can't figure it out.
/
Here is a clip of code:
switch(!0) {
case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
case ($.isFunction(s.data)): //...
break;
}
I saw a piece of code that stuck me as odd. What does switch(!0) mean in javascript? What are some cases where this technique would be useful to use?
jsTree uses it in a few places but it looks foreign. I'm sure it has a good reason behind it, but can't figure it out.
http://www.jstree./
Here is a clip of code:
switch(!0) {
case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
case ($.isFunction(s.data)): //...
break;
}
Share
Improve this question
asked Aug 10, 2012 at 23:37
MMeahMMeah
1,0421 gold badge9 silver badges18 bronze badges
4
-
2
Someone is trying to obfuscate their code I'd say. This is a hacky way to not use
if
andif else
. – Torsten Walter Commented Aug 10, 2012 at 23:41 - possible duplicate of What does !1 and !0 mean in Javascript? – user1106925 Commented Aug 11, 2012 at 0:00
- 1 Because sensical code is too mainstream. Also, I say we should name these Yoda switches. – Mahn Commented Aug 11, 2012 at 0:13
- @Mahn HA! I am for the new term. +1 the ment if you like the new term "Yoda switches" – MMeah Commented Aug 12, 2012 at 7:35
2 Answers
Reset to default 9It's paring each of the cases to boolean true
.
Elaborating
case (!s.data && !s.ajax)
If !s.data && !s.ajax
evaluates to true
, then this case will be selected for execution.
switch(true)
is the same as switch(!0)
A switch(!0)
is simply the same as switch(true)
.
This pattern:
switch (true) {
case (condition): do something; break;
case (condition): do something; break;
case (condition): do something; break;
}
Works the same as:
if (condition) {
do something;
} else if (condition) {
do something;
} else if (condition) {
do something;
}