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


There’s a lot more on conditional statements (switch, if), logical operators, JS function, JS variables, JS methods, APIs, etc to create/build/publish a web app with a full commentary & source code in my ebook What The Hekk is HTML/CSS/JS? !

dedicated assistance to your jekyll website, blog, portfolio, or project (fiverr gig @whatthehekkist) dedicated assistance to your jekyll website, blog, portfolio, or project (fiverr gig @whatthehekkist)



What The Hekk is HTML/CSS/JS? a complete guide to creating a web app in 5 min from scratch!

Kindle Edition

What The Hekk is HTML/CSS/JS? a complete guide to creating a web app in 5 min from scratch!

PDF






You May Also Enjoy

  • Web Dev

    Bootstrap Nav, Browser inspection, and Browser rendering process

    2023-04-23

    # Bootstrap navigation Bootstrap navigation is one of the most widely used navigation templates and there are a lot of practical points that help get familiar with **frontend**. In this post, we are going to have a close look at...

  • Web Dev

    Live CSS trainer v2.0

    2023-07-03

    validate your css codes LIVE without auto-completion    ✔️ write css code manually!    ✔️ copy & paste may not work!    ✔️ hover or click HTML element on each question to...

  • 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

    [Gitpod] 웹에서 코딩하기

    2022-07-12

    [Gitpod](https://www.gitpod.io/)은 오픈소스 원격 개발 플랫폼이다. 이미 굉장히 많은 사용자들이 있고, 이 블로그 또한 처음부터 Gitpod 사용했다. 개인적으로 생각하는 Gitpod의 가장 큰 장점은 사용자가 본인 컴퓨터에 로컬 개발환경 세팅에 시간을 너무 많이 투자해야 할 필요가 없고, 모든 걸 Gitpod이 제공하는 원격...

  • 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 is...