Skip to main content

Command Palette

Search for a command to run...

JavaScript Switch Statements

Published
2 min readView as Markdown
JavaScript Switch Statements
E

I'm a full-stack web developer who loves building new projects and learning new things

It might not show from my posts, but I'm also quite funny.

In this post, we will be learning about JavaScript switch statements.

A Switch statement takes a variable, checks its value, and then depending on the value executes the code starting from a different point.

The Javascript Switch Statement

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

JavaScript Code

switch (x) {
  case 0:
  y="a";
    break;
  case 1:
y = "b";
    break;
  case 2:
     y = "c";
    break;
default:
  y = "d";
    break;
}

Important Note

One very important thing that is easy to get wrong with the switch statement is the variable only determines the starting point of the statement. As an observant person, you probably saw that each block of code ends with a break statement. This is required because without a break statement, the statement will keep on executing; the value of the variable x only determines where the code starts executing rather than which blocks are executed. So without an intervening "break", all the code below your starting point will execute.

Default keyword

The default keyword means if the variable doesn’t match any of the values, then start executing the code from here.

Javascript Code

switch (x) {
  case 0:
  y="a";
    break;
case 1:
y = "b";
    break;
case 2:
     y = "c";
    break;
default:
  y = "d";
    break;
}

Result

Image description

More from this blog

Javasper

50 posts

I'm a full stack software developer who loves to building new projects and solving difficult problems.

It might not be obvious from my posts, but I'm actually quite funny.