Switch Statements in JavaScript and TypeScript - Simple & Code Examples

Switch Statements in JavaScript and TypeScript - Simple & Code Examples

Switch statements are a type of control flow statement in programming languages such as JavaScript and TypeScript. These statements are used when we want to execute different code based on the value of a single variable or expression.

In JavaScript and TypeScript, switch statements are commonly used for cases where there are multiple conditions to evaluate, but only one outcome should be executed. The syntax of a switch statement in JavaScript and TypeScript is quite similar.

Here is the basic syntax for a switch statement in JavaScript:

switch (expression) {
  case value1:
    // code to execute if expression matches value1
    break;
  case value2:
    // code to execute if expression matches value2
    break;
  ...
  default:
    // code to execute if expression does not match any of the values
}

The syntax for a switch statement in TypeScript is almost identical:

switch (expression) {
  case value1:
    // code to execute if expression matches value1
    break;
  case value2:
    // code to execute if expression matches value2
    break;
  ...
  default:
    // code to execute if expression does not match any of the values
}

Differences between JSand TS Switch statements

The main difference between JavaScript and TypeScript Switch statements is that TypeScript requires you to declare the type of the expression being switched on. For example:

let fruit: string = 'apple';

switch (fruit) {
  case 'apple':
    console.log('You selected an apple.');
    break;
  case 'banana':
    console.log('You selected a banana.');
    break;
  default:
    console.log('You selected something else.');
}

Here, the variable fruit is declared as a string, and the switch statement evaluates the value of fruit to determine which case to execute.

Using Switch Statements

In JavaScript

we can use switch statements to perform a variety of tasks. For example, we can use them to evaluate user input and execute different code depending on the user's choice. Here is an example of a switch statement in JavaScript that evaluates the value of a user's input and displays a different message based on the input:

let userInput = prompt("Enter a number between 1 and 3:");

switch (userInput) {
  case "1":
    alert("You entered one.");
    break;
  case "2":
    alert("You entered two.");
    break;
  case "3":
    alert("You entered three.");
    break;
  default:
    alert("Invalid input.");
}

In TypeScript

switch statements can also be used to evaluate user input and execute different code depending on the input. Here is an example of a switch statement in TypeScript that evaluates the value of a user's input and displays a different message based on the input:

let userInput: number = parseInt(prompt("Enter a number between 1 and 3:"));

switch (userInput) {
  case 1:
    console.log("You entered one.");
    break;
  case 2:
    console.log("You entered two.");
    break;
  case 3:
    console.log("You entered three.");
    break;
  default:
    console.log("Invalid input.");
}

In this example, the user input is first parsed as an integer using the parseInt function. Then, the switch statement evaluates the value of userInput to determine which case to execute.

Using Switch Statements in TypeScript with Enums

Switch statements are also commonly used in conjunction with enums in TypeScript. Enums are a way to define a set of named constants, which can then be used in switch statements to provide type safety and avoid hardcoding values.

Here is an example of enum in TypeScript:

enum Color {
  Red = 1,
  Green = 2,
  Blue = 3
}

In this example, we define an enum called Color with three named constants: Red, Green, and Blue. Each constant is assigned a value, starting from 1.

We can then use this enum in a switch statement to perform different tasks depending on the value of the enum. Here is an example:


let selectedColor: Color = Color.Green;

switch (selectedColor) {
  case Color.Red:
    console.log("You selected red.");
    break;
  case Color.Green:
    console.log("You selected green.");
    break;
  case Color.Blue:
    console.log("You selected blue.");
    break;
  default:
    console.log("Invalid color.");
}

In this example, we define a variable called selectedColor and assign it the value Color.Green. We then use a switch statement to evaluate the value of selectedColor and execute the appropriate code.

Using Switch Statements in TypeScript with Interfaces

In TypeScript, it is possible to use switch statements with interfaces, but whether or not it is a good practice depends on the context of your code.

If you have a set of objects that all implement the same interface and you need to perform different logic based on their specific type, then you could use a switch statement on the object's type. For example:

interface Animal {
  type: string;
  makeSound(): void;
}

class Dog implements Animal {
  type = 'dog';
  makeSound() {
    console.log('Woof!');
  }
}

class Cat implements Animal {
  type = 'cat';
  makeSound() {
    console.log('Meow!');
  }
}

function makeAnimalSound(animal: Animal) {
  switch(animal.type) {
    case 'dog':
      animal.makeSound();
      break;
    case 'cat':
      animal.makeSound();
      break;
    default:
      console.log('Unknown animal type');
      break;
  }
}

const myDog = new Dog();
makeAnimalSound(myDog); // Output: Woof!

const myCat = new Cat();
makeAnimalSound(myCat); // Output: Meow!

In this example, the makeAnimalSound function takes an Animal object and switches on its type property to determine which specific sound to make. This is a common pattern in object-oriented programming and can be a useful way to handle different types of objects that share a common interface.

However, if you find yourself using a switch statement on an interface frequently, it might be a sign that your code could be refactored to be more object-oriented. In general, it's a good practice to favor polymorphism over switch statements when working with object-oriented code.

Overall, switch statements are a powerful tool in JavaScript and TypeScript for performing different tasks based on the value of a single variable or expression. They are commonly used in situations where there are multiple conditions to evaluate, but only one outcome should be executed. With enums in TypeScript, switch statements can provide type safety and avoid hardcoding values, making them a valuable tool for any TypeScript developer.