Search⌘ K

Switch Scope

Explore how switch statements control scope in TypeScript and the importance of using curly braces for each case. Learn to prevent variable sharing issues and write clearer, safer code in conditional flows.

We'll cover the following...

A switch statement is similar to an if statement. The condition set between the two parentheses must be met to reach one of the cases. If not, the default case will be entered.

TypeScript 3.3.4
function switchFunction(a: number): void {
switch (a) {
case 1:
let variableInCase1 = "test";
console.log(variableInCase1);
break;
case 2:
let variableInCase2 = "test2";
console.log(variableInCase2);
break;
default:
console.log("Default");
}
}
switchFunction(1);
switchFunction(2);
switchFunction(3);

Not adding the keyword break ...