Switch Statements

Overview

Overviewvisual1

A switch statement is used to run different code blocks depending on the value of an expression.

switch (theExpression) {
  case valueA:
    // Code block if theExpression === valueA
    break;
  
  case valueB:
    // Code block if theExpression === valueB
    break;
  
  case valueC:
    // Code block if theExpression === valueC
    break;
  
  default:
    // Code block if theExpression doesn't match any cases
    break;
}

At the top of the switch statement, theExpression is evaluated. The value of theExpression is then compared to the value in each case. The switch statement uses strict comparison (===), which means the values must be of the same type. Visit the lesson on variables to learn more about data types and loose typing.

The switch statement runs the first code block where the comparison is true. The break statement, which is optional, tells the program to exit the switch statement at the end of the code block. If none of the cases are true, then the switch statement runs the code block for the default case.

Use Cases to Draw Different Messages

In this example, we compare the value stored in the variable option to select which message to draw. If option === 0, then the code block in case 0 is run and we draw the message "You chose option 0." Change the value assigned to the variable option to a different number between 0-4 to see what the code in those other cases does.

To learn more about variables, visit the Variables lesson.

Quick Reference: Coordinates Variables fillStyle

Editor (write code below)
var canvas = document.getElementById('switch_statements_example1'); var context = canvas.getContext('2d'); var option = 0; // Assign option a number from 0-4 switch (option) { case 0: context.font = '16px Arial'; context.fillStyle = 'Black'; context.fillText('You chose option 0.', 20, 40); break; case 1: context.font = '24px Arial'; context.fillStyle = 'Crimson'; context.fillText('Yay! Option 1!', 200, 200); break; case 2: context.font = '36px Arial'; context.fillStyle = 'DarkMagenta'; context.fillText('Groovy, man. Option 2.', 80, 160); break; case 3: context.font = 'bold 48px Arial'; context.fillStyle = 'DeepPink'; context.strokeStyle = 'DarkSlateBlue'; context.lineWidth = 4; context.textAlign = 'center'; context.translate(220, 150); context.rotate(-Math.PI / 9); context.strokeText('Wow! Option 3!', 0, 0); context.fillText('Wow! Option 3!', 0, 0); break; case 4: context.font = 'bold 48px Arial'; context.fillStyle = 'SeaGreen'; context.translate(10, 120); context.fillText('MIRROR OPTION 4', 0, 0); context.scale(1, -3); var gradient = context.createLinearGradient(0,0,0,-32); gradient.addColorStop(0,'rgba(0, 0, 0, 1)'); gradient.addColorStop(1,'rgba(0, 0, 0, 0)'); context.fillStyle = gradient; context.fillText('MIRROR OPTION 4', 0, 0); break; }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 1

Challenge1visual1
Your switch statement should draw one of these rectangles

The switch statement below uses the value assigned to the variable rectangleType to select which type of rectangle to draw.

If rectangleType === 'A', then draw a rectangle with a width of 45 and height of 100 at the position (20, 20) filled with the color 'Red'.

If rectangleType === 'B', then draw a rectangle with a width of 45 and height of 100 at the position (75, 20) filled with the color 'Yellow'.

If rectangleType === 'C', then draw a rectangle with a width of 100 and height of 100 at the position (20, 130) filled with the color 'Green'.

If rectangleType === 'D', then draw a rectangle with a width of 100 and height of 210 at the position (130, 20) filled with the color 'Blue'.

Change the value assigned to the variablerectangleTypeto draw each of the four rectangles. The switch statement should only draw one rectangle at a time. If your program seems to be working, mark the challenge as complete by selecting "Yes, it looks good".

If you need help setting fill colors and drawing rectangles, visit the fillStyle and fillRect() lessons.

Quick Reference: Coordinates Variables fillRect() fillStyle

Editor (write code below)
var canvas = document.getElementById('switch_statements_challenge1'); var context = canvas.getContext('2d'); var rectangleType = 'A'; switch (rectangleType) { // ADD CASES IN HERE }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge1

Include a Default Case

In this example, we use a switch statement to change the expression on Rectangle Man's face.

Change the value of the parameter expression to 'happy', 'angry', or 'scared' to see Rectangle Man's expression change. Note that those values are text strings, and the case values are also text strings to match. If we enter drawFace(happy), he won't be happy. We have to enter drawFace('happy').

We have also included a default case at the bottom of the switch statement. If we enter an expression that Rectangle Man doesn't recognize, such as drawFace('sad'), the switch statement runs the default code black. This is useful because, if we enter drawFace() with no value for expression, we get Rectangle Man's default expression.

To learn more about functions and variables, visit the Function and Variables lessons.

Quick Reference: Coordinates Variables Functions fillRect() fillStyle save() / restore() translate()

Editor (write code below)
var canvas = document.getElementById('switch_statements_example2'); var context = canvas.getContext('2d'); context.translate(200, 20); drawFace('happy'); // Change Rectangle Man's expression to 'happy', 'angry', 'scared', or none function drawFace(expression) { context.save(); context.fillStyle = '#000000'; context.strokeStyle = '#000000'; context.strokeRect(-80, 0, 160, 280); // Draw head context.strokeRect(-15, 120, 30, 60); // Draw nose context.strokeRect(15, 160, 10, 20); // Draw right nostril context.strokeRect(-25, 160, 10, 20); // Draw left nostril switch (expression) { case 'happy': context.strokeRect(20, 80, 30, 30); context.fillRect(29, 89, 12, 12); context.strokeRect(-50, 80, 30, 30); context.fillRect(-41, 89, 12, 12); context.strokeRect(-45, 200, 90, 30); for (var i = 0; i < 6; i = i + 1) { context.strokeRect(-45 + 15 * i, 200, 15, 15); context.strokeRect(-45 + 15 * i, 215, 15, 15); } break; case 'angry': context.strokeRect(15, 90, 40, 10); context.fillRect(25, 90, 10, 10); context.strokeRect(-55, 90, 40, 10); context.fillRect(-35, 90, 10, 10); context.strokeRect(-40, 200, 80, 10); break; case 'scared': context.strokeRect(20, 75, 30, 40); context.fillRect(28, 88, 14, 14); context.strokeRect(-50, 75, 30, 40); context.fillRect(-42, 88, 14, 14); context.strokeRect(-25, 200, 50, 60); break; default: context.strokeRect(20, 80, 30, 30); context.fillRect(30, 90, 10, 10); context.strokeRect(-50, 80, 30, 30); context.fillRect(-40, 90, 10, 10); context.strokeRect(-30, 200, 60, 20); break; } context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 2

Challenge2visual1
What your drawing should look like

The drawFlag() function uses three parameters (x, y, and country) to draw a flag at the position (x, y). Create a switch statement inside the function so it draws a French flag if country === 'France', a Colombian flag if country === 'Colombia', or a simple white flag if country is undefined or has some other value.

Then, use the drawFlag() function to draw a French flag at (200, 10), a Colombian flag at (10, 90), and a white flag at (200, 170).

To draw a French flag, use:

context.fillStyle = '#0055A4';
context.fillRect(0, 0, 60, 120);
context.fillStyle = '#FFFFFF';
context.fillRect(60, 0, 60, 120);
context.fillStyle = '#EF4135';
context.fillRect(120, 0, 60, 120);

To draw a Colombian flag, use:

context.fillStyle = '#FCD116';
context.fillRect(0, 0, 180, 60);
context.fillStyle = '#003893';
context.fillRect(0, 60, 180, 30);
context.fillStyle = '#CE1126';
context.fillRect(0, 90, 180, 30);

To draw a white flag, use:

context.fillStyle = '#FFFFFF';
context.fillRect(0, 0, 180, 120);
Editor (write code below)
var canvas = document.getElementById('switch_statements_challenge2'); var context = canvas.getContext('2d'); // DRAW THE FRENCH FLAG AT (200, 10) HERE // DRAW THE COLOMBIAN FLAG AT (10, 90) HERE // DRAW THE WHITE FLAG AT (200, 170) HERE function drawFlag(x, y, country) { context.save(); context.translate(x, y); // CREATE THE SWITCH STATEMENT TO DRAW THE FRENCH, COLOMBIAN, OR WHITE FLAG HERE context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge2

Chain Together the Code in Multiply Cases

A break statement tells the program to exit a switch statement at the end of a code block. If there is no break statement at the end of a code block, the program continues to run the code in the next code block.

In this example, we use a switch statement to draw Rectangle Man's face with some bling. Try passing values from 0 (no bling) to 4 (max bling) into the drawFaceWithBling() function to see how Rectangle Man's bling changes.

Because we are not ending the code blocks in each case with a break statement, the program does not exit the switch statement when the code block is done. For example, if we pass a value of 2 into the parameter bling, then case 2 in the switch statement will be true, and the program will run that code block. But when that code block is over, the program will continue running the code in the code blocks below, even if those cases are false, until it reaches a break statement or the switch statement ends.

By leaving out the break statements for each case, Rectangle Man gets the bling from both case 2 and case 1 if we pass the bling parameter a value of 2, and he gets all the bling if we pass the bling parameter a value of 4.

Quick Reference: Coordinates Variables Functions fillRect() fillStyle save() / restore() translate()

Editor (write code below)
var canvas = document.getElementById('switch_statements_example3'); var context = canvas.getContext('2d'); context.translate(200, 50); drawFaceWithBling(0); // Give Rectangle Man some bling (0-4); function drawFaceWithBling(bling) { context.save(); context.fillStyle = '#000000'; context.strokeStyle = '#000000'; context.strokeRect(-64, 0, 128, 224); context.strokeRect(-12, 96, 24, 48); context.strokeRect(12, 128, 8, 16); context.strokeRect(-20, 128, 8, 16); context.strokeRect(16, 64, 24, 24); context.fillRect(24, 72, 8, 8); context.strokeRect(-40, 64, 24, 24); context.fillRect(-32, 72, 8, 8); context.strokeRect(-24, 160, 48, 16); context.strokeRect(64, 80, 12, 30); context.strokeRect(-76, 80, 12, 30); switch (bling) { case 4: // Draw necklace context.save(); context.translate(0, 132); context.fillStyle = '#EECC00'; context.fillRect(-16, 104, 32, 60); context.rotate(-Math.PI / 5); for (var i = 0; i < 9; i = i + 1) { context.fillRect(-8, 114, 16, 40); context.rotate(Math.PI / 20); } context.restore(); case 3: // Draw earring context.save(); context.fillStyle = '#EECC00'; context.fillRect(-76, 110, 8, 8); context.fillRect(-76, 120, 8, 8); context.fillRect(-76, 130, 8, 8); context.fillRect(-77, 140, 10, 16); context.restore(); case 2: // Draw hat context.save(); context.fillRect(-68, -40, 136, 88); context.fillRect(-88, 40, 176, 8); context.fillStyle = 'FireBrick'; context.fillRect(-68, 16, 136, 24); context.restore(); case 1: // Draw sunglasses context.save(); context.fillRect(-72, 72, 144, 8); context.fillStyle = '#660000'; context.fillRect(2, 64, 56, 24); context.fillRect(-58, 64, 56, 24); context.restore(); } context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 3

Challenge3visual1
What your drawing should look like

Right now, the drawRedDoor() function uses two parameters to draw a red door at the position (x, y).

Re-write the function so it accepts a third parameter, detailLevel. Draw the door's red rectangle first. Then, add the door knob if the detailLevel is greater than or equal to 1, the door's window if it is greater than or equal to 2, and the mail slot if it is equal to 3.

Draw a red door with detailLevel === 1 at (10, 20), detailLevel === 2 at (140, 20), and detailLevel === 3 at (270, 20).

Editor (write code below)
var canvas = document.getElementById('switch_statements_challenge3'); var context = canvas.getContext('2d'); drawRedDoor(10, 20); drawRedDoor(140, 20); drawRedDoor(270, 20); function drawRedDoor(x, y) { context.save(); context.translate(x, y); context.fillStyle = '#FF0000'; context.fillRect(0, 0, 120, 240); // Red rectangle context.fillStyle = '#99CCFF'; context.fillRect(20, 20, 80, 60); // Window context.fillStyle = '#FFD700'; context.fillRect(90, 120, 16, 16); // Door knob context.fillRect(40, 180, 40, 16); // Mail slot context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)
Challenge3

Handle keydown Events

In this example, we use a switch statement to handle keydown events. Select the canvas below by clicking on it. Then, use the arrow or WASD keys to move the square on the canvas.

There is a lot happening in this example, but the part of the program we want to focus on is the moveSquare() function, which is registered to listen for keydown events on the canvas.

canvas.addEventListener('keydown', moveSquare);

If a key is pressed down while the canvas is selected, a keydown event is generated and passed into the moveSquare() function, where it is then stored in the parameter e.

function moveSquare(e) {
  switch (e.keyCode) {
    case 37:
    case 65:
      x -= 10; // Left
      break;
    
    case 38:
    case 87:
      y -= 10; // Up
      break;
    
    case 39:
    case 68:
      x += 10; // Right
      break;
    
    case 40:
    case 83:
      y += 10; // Down
      break;
  }
  
  drawSquare();
  e.preventDefault();
}

Inside the moveSquare() function, we can identify the key that was pressed by accessing the keydown event's keyCode property. We use a switch statement to move the square to the left by subtracting 10 from it's x-coordinate if the left arrow (e.keyCode === 37) or the a-key (e.keyCode === 65) has been pressed, and we move the square to the right by adding 10 if the right arrow (e.keyCode === 39) or the d-key (e.keyCode === 68) has been pressed. Note that if e.keyCode === 37, the code block for e.keyCode === 65 runs because there is no break statement between them. Finally, we redraw the square at its new position using the drawSquare() function. Here is a list of keyCode values.

To learn more about handling events, visit the addEventListener() lesson.

Quick Reference: Coordinates Functions fillRect() fillStyle save() / restore()

Editor (write code below)
var canvas = document.getElementById('switch_statements_example4'); var context = canvas.getContext('2d'); var x = 50; var y = 50; canvas.addEventListener('blur', pause); canvas.addEventListener('focus', play); canvas.addEventListener('keydown', moveSquare); pause(); function moveSquare(e) { switch (e.keyCode) { case 37: case 65: x -= 10; // Left break; case 38: case 87: y -= 10; // Up break; case 39: case 68: x += 10; // Right break; case 40: case 83: y += 10; // Down break; } drawSquare(); e.preventDefault(); } function drawSquare() { context.save(); context.clearRect(0, 0, canvas.width, canvas.height); context.fillStyle = 'Orange'; context.fillRect(x, y, 40, 40); context.restore(); } function play() { drawSquare(); context.save(); context.font = '16px Arial'; context.textAlign = 'center'; context.fillStyle = 'Black'; context.fillText('Use the arrow or WASD keys to move the square', canvas.width / 2, canvas.height / 2); context.restore(); } function pause() { drawSquare(); context.save(); context.font = '16px Arial'; context.textAlign = 'center'; context.fillStyle = 'Black'; context.fillText('Click to select the canvas', canvas.width / 2, canvas.height / 2); context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Challenge 4

Inside the setColor() function, add a switch statement that will change the color of the square depending on the key pressed.

Assign the context.fillStyle property the color 'Red' if the r-key is pressed (keyCode 82), the color 'Orange' if the o-key is pressed (keyCode 79), the color 'Yellow' if the y-key is pressed (keyCode 89), the color 'Green' if the g-key is pressed (keyCode 71), the color 'Blue' if the b-key is pressed (keyCode 66), the color 'Indigo' if the i-key is pressed (keyCode 73), and the color 'Violet' if the v-key is pressed (keyCode 86).

All you have to do is add the switch statement. The rest of the program has been set up for you.

Try changing the color of the square by pressing the ROYGBIV keys. If your program seems to be working, mark the challenge as complete by selecting "Yes, it looks good".

Editor (write code below)
var canvas = document.getElementById('switch_statements_challenge4'); var context = canvas.getContext('2d'); canvas.addEventListener('blur', pause); canvas.addEventListener('focus', play); canvas.addEventListener('keydown', setColor); context.fillStyle = 'Green'; pause(); function setColor(e) { // ADD SWITCH STATEMENT HERE drawSquare(); e.preventDefault(); } function drawSquare() { context.save(); context.clearRect(0, 0, canvas.width, canvas.height); context.translate(canvas.width / 2 - 120, canvas.height / 2 - 120); context.fillRect(0, 0, 240, 240); context.restore(); } function play() { drawSquare(); context.save(); context.font = '16px Arial'; context.textAlign = 'center'; context.fillStyle = 'Black'; context.fillText('Use the ROYGBIV keys to change the color of the square', canvas.width / 2, canvas.height / 2); context.restore(); } function pause() { drawSquare(); context.save(); context.font = '16px Arial'; context.textAlign = 'center'; context.fillStyle = 'Black'; context.fillText('Click to select the canvas', canvas.width / 2, canvas.height / 2); context.restore(); }
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Ready for the next lesson?

Next up, the "While Loops" lesson >