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? !

convert your manuscript to epub (fiverr gig @whatthehekkist) convert your manuscript to epub (fiverr gig @whatthehekkist) 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

    What are domain, nameserver, and DNS?

    2023-04-12

    # domain, nameserver, and DNS When you visit a website, there's a lot going on behind your computer until you actually view the website. In this post, you will learn the process of DNS resolution in detail and will...

  • 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;}    ✔️...

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

  • Music

    100 famous rap lyrics in the world

    2023-08-17

    1. "I came, I saw, I conquered. Or should I say, I saw, I conquered, I came." - Jay Z, "Izzo (H.O.V.A)" (United States) 2. "If I say I'm going to die today, I'm going to die today." - Eminem,...

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

  • ebook

    6 Useful Hacks for ebook Publish in 2023

    2023-07-19

    # Choose a legit ebook editing software/program If you plan to write and publish an ebook, it's best practice to pick a robust ebook editing program for your manuscript. There are plenty of ebook editing softwares/programs you can go for...