Javascript Switch

In every programming language there are many-many conditions. Conditions are very usable and very necessary things in programming, that's why all programming languages have declaration of conditions.

In every programming languages there is If operator.

So let's see a little about if and if..else statements.

Javascript If statement

Like every programming language, javascript has If statement. Its syntax is:

if(...any conditionA...)
{
   //...if conditionA is true
}

If we want to have condition "true" and "false" side, we use if..else

if(...any conditionA (condition can be logical actions)...)
{
   //...if conditionA is true
}
else
{
   //...if conditionA is false
}

Now let's imagine we have more things to check and do some actions, for example we have any circles with different colors: red, blue, green, yellow, black, white and brown and we want to group these circles by color.

Let's make it with javascript using arrays for every group.

var circles = [{color: 'red'},{color: 'yellow'},{color: 'red'},{color: 'yellow'}...];
var redCircles = [];
var yellowCircles = [];

So how we ganna do that? You understand, that we're not going to make very long code using If or if..else. Javascript has Switch statement for this situation.

Javascript Switch

Syntax

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}

Now let's continue our work.

In this example we will use javascript for loop, so you can learn about it Here.

We will use javascript arrays too, and you can learn about it Here.

<!DOCTYPE html>
<html>
  <body> 
    <ul>
       <li id="red"></li>
       <li id="yellow"></li>
    </ul>
    <script>
       var circles = [{color: 'red'},{color: 'yellow'},{color: 'red'},{color: 'yellow'}];
       var redCircles = [];
       var yellowCircles = [];
       
       for(var i = 0; i < circles.length; i++){
          switch(circles[i].color){
             case 'red':
                redCircles.push(circles[i]);
                break;
             case 'yellow':
                yellowCircles.push(circles[i]);
                break;
             default:
                 break;
          }
       }
 
       document.getElementById("red").innerHTML = redCircles[0].color;
       document.getElementById("yellow").innerHTML = yellowCircles[0].color;
    </script>
  </body>
</html>