Skip to main content

Command Palette

Search for a command to run...

Why use switch instead of if in javascript

Advantages of switch over if-else

Updated
1 min read
Why use switch instead of if in javascript
S

React js developer

When we have several conditions, using of Switch instead of if in javascript, is Clear.

#advantages of switch over if-else:#

  1. switch statement works much faster than an equivalent if-else
  2. It’s more readable

Look at this code:

if (x === 15) {
  alert("Ten");
}

when we use switch it convert to:

switch(x) {
  case 15:
    alert("fifteen");
}

in if code, we use Strict Equality Operator === and this Comparison is in switch.

if you need more information about switch, read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

what is switch in javascript:

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered.

what to do if no case matches the expression's value?

we use default. The default clause of a switch statement will be jumped to if no case matches the expression's value.

Notice at if and witch code below pictures. first if code:

if code in javascript syntax.jpg

then we write above cod to switch statements:

switch statements syntax in javascript.jpg

More from this blog