what is switch statement?

switch statement is a conditional statement in JS (and in most programming languages) to execute a certain action over multiple inner blocks called case.

switch takes an expression (input condition) that looks for a match case by comparing its value with the values defined in each case.

 switch (expression) {  
    case a:
      // code block
      break;

    case b:
      // code block
      break;

    case c:
      // code block
      break;
     
    default:
      // code block
      break;
  }

switch statement; example 1

Let’s have a look at an example.
The following is a block of codes in JS that alerts a matching case (matching number) in browser, given that expression in switch statement is a random number generated between 0, 1, and 2.

let match = Math.floor(Math.random() * 3); //a random integer from 0 to 2
let a=0,b=1,c=2; //case a, b, and c

switch (match) {  
  case a:
    alert("I got number " + a);
    break;

  case b:
    alert("I got number " + b);
    break;

  case c:
    alert("I got number " + c);
    break;
    
  default:
    alert("no match found");
    break;
}


The code match = Math.floor(Math.random() * 3); first generates a random number within its range and the variable match is ready as an expression.
The expression (match) in switch statement then looks for a match by comparing its value with each case and returns the associated code in a match case as seen below.

switch statement


The key logic behind switch statement is the strict equality operator === which checks whether its two operands are equal in value & type. That means, switch is an equal to statement specialized in checking an equality (match) between expression and multiple case clauses to make different decisions.

The example switch statement above can be explained as multiple if statements with the strict equality operator ===. Both of the statements do the same job looking for an equality (match), and it’s seen that switch statement simplifies process, as opposed to if statement going verbose relatively. However, either way is still fine as it’s mere a few case clauses in switch statement (, and if-elseif-else clauses in if statement) only.

switch-vs-if
switch vs if


What if considering different actions/decisions (more than 5+)? You probably don’t want to or have to go for if statement.
switch statement will execute different decision codes -one at a time- only if an expression (input condition) finds a match across multiple target case clauses (target conditions). switch statement doesn’t only simplify process and readability, but also delivers faster performance.

switch-vs-if
switch vs if


To sum up, all of conditional statements in JS take an expression (input condition).

switch statement; example 2

facestyling.click is a face shape recognition web application that suggests fashion/accessory items by AI-analyzing face shape of an input image among oval, round, long, square, and triangle in percentage. To deliver users different fashion item recommendations depending on face shape results the AI analyzes, switch statement performs a significant role.

Say, you upload a face image to the input form and then the AI trained with a number of face images predicts the best matching face shape for the input image at runtime. After that, based on the prediction data the AI returns, switch statement looks for and returns a match case in multiple case clauses where contain pre-defined fashion/accessory recommendations by face shape.

switch statement example at facestyling.click





You May Also Enjoy

  • Network

    [Packet Tracer] Configuring a DHCPv4 Server and a Relay Agent

    2022-07-14

    [Cisco Network Academy](https://www.netacad.com/) provides plenty of learning resources in networking. I will cover how to configure basic DHCPv4 on a router and a DHCPv4 Server, and a DHCP relay agent using [Packet Tracer](https://www.netacad.com/courses/packet-tracer) where you can simulate network topologies and...

  • Web Dev

    how to use git

    2023-04-09

    Git is a version control system where you can upload, update, and track the source code of your project. Also, you can easily deploy codes in your Git repository to a deployment/hosting platform. There are so many benefits...

  • Web Dev

    Nelify에 Jekyll 웹사이트 배포하기

    2022-07-10

    정적 웹사이트나 블로그에 관심이 많다면 [Jekyll](http://Jekyllthemes.org/)에 대해 들어 봤을 것이다. 간단한 구글링만으로도 Jekyll을 사용하여 어떻게 웹사이트나 블로그를 만드는지 쉽게 알 수 있다. 이 블로그 또한 Jekyll 기반이고, [Better Jeong](https://betterjeong.github.io/blog/21042701/)님과 [Jihye Leee](https://www.jihyeleee.com/blog/third-designer-can-make-Jekyll-blog/)님의 블로그 포스트를 참고하여 커스터마이징하였다. # Nelify에 배포하기 Jekyll기반 블로그를...

  • Web Dev

    [JS variables] what is var, let, and const?

    2023-04-08

    In any script/programming language, variable is a logical storage where you can assign value into, and JS has three types of variables; var, let, and const. Let’s get familiar with some of the variable-related terms first. Declaration...

  • Programming

    Image crawling with Python on Chrome browser

    2022-07-09

    Step by step insturction ## 1. Install selenium and beautiful soup on terminal ```python pip install bs4 pip install pip install selenium ``` ##...

  • Web Dev

    Live CSS trainer v1.0

    2023-06-22

    <h1>validate your css codes LIVE</h1> <h1>without auto-completion</h1> <p>    ✔️ write css code manually!    ✔️ example #1: type   * {color: blue;}    ✔️ example #2: type   html {background-color: grey;}    ✔️...