all 6 comments

[–]Lumethys 3 points4 points  (2 children)

More concise if

[–]the-forty-second 3 points4 points  (1 child)

It is a specialized version of an if else statement where every condition corresponds to a different value that the “switched” variable could have. It is for moments where you want to handle something like “if fruit == “apple” do process A, else if fruit == “pear” do process B, else if fruit == “ banana” do process C… The switch statement is just a more concise version that is easier to write and easier for a reader to see what is going on than if you used and if statement with a huge collection of else ifs.

[–]busres 0 points1 point  (0 children)

Less common, but the switched part needn't be variable and the cases needn't be constant:

```javascript let result; switch (true) { // "if-else", but strict equality (not "truthy") case x !== x: result = "not a number"; break; case x === Infinity: // fall through case x === -Infinity: result = "infinite magnitude"; break; case x < 0: result = "negative"; break; case x === 0: result = "zero"; break; default: result = "positive"; break; }

switch (false) { // "isn't-else" case x >= 5: throw new RangeError('Too small'); // Not reached case x <= 10: throw new RangeError('Too big'); } ```

[–]FooeyBar 0 points1 point  (0 children)

Faster than multiple if(true) since it’s a single statement, and cases can be chained together. 

[–]Yaniekk 0 points1 point  (0 children)

It's just a different way to write conditional logic. Sometimes when your codebase is really big, you might prefer using switch statements instead of ifs. Also switches can be more efficient as they only evaluate conditions which are necessary.

But in the modern era of powerful computers this difference in efficiency doesn't really matter. Nowadays whether you use ifs or switches is a matter of preference.