Switch (! 0) What does it mean

I saw a piece of code that stuck in me as weird. What does switch (! 0) mean in javascript? What are some cases where this method will be useful to use?

jsTree uses it in several places, but looks alien. I am sure that this has a good reason, but I can’t understand.

http://www.jstree.com/

Here is the code snippet:

switch(!0) {
    case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
    case ($.isFunction(s.data)): //...
                                 break;
}
+5
source share
2 answers

He compares each case with boolean true.

developed

case (!s.data && !s.ajax)

If !s.data && !s.ajaxevaluated as true, then this case will be selected for execution.

switch(true) coincides with switch(!0)

+9
source

A switch(!0)just matches switch(true).

This template:

switch (true) {
  case (condition): do something; break;
  case (condition): do something; break;
  case (condition): do something; break;
}

It works the same way:

if (condition) {
  do something;
} else if (condition) {
  do something;
} else if (condition) {
  do something;
}
+2
source

All Articles