Switch Statements in Javascript
The switch statement evaluates an expression and executes code based on matching cases. It’s an efficient alternative to multiple if-else statements, improving readability when handling many conditions.
Basic Syntax
switch (expression) {
case value1:
// Code to run if expression === value1
break;
case value2:
// Code to run if expression === value2
break;
default:
// Code to run if no cases match
}
The break keyword written inside every case stops the remaining checks. Without the break keyword, the code will continue running the next cases, even if they don’t match with expression.
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);//Wednesday
default keyword
The default keyword in a JavaScript switch statement specifies a block of code to run if no case matches the evaluated expression. It behaves identically to the final else block in an if / else if / else conditional chain.
const fruit = "Papaya";
switch (fruit) {
case "Banana":
console.log("Bananas are $0.48 a pound.");
break;
case "Apple":
console.log("Apples are $0.32 a pound.");
break;
default:
console.log('Sorry, we do not have prices for ${fruit}'.);
}
// Output: 'Sorry, we do not have prices for Papaya'.
Difference Between Global scope, function scope, and block scope
Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within {}) they are declared in.Variables declared with let or const within a block (e.g., within {}) are only accessible within that block. This is not true for var, which is function-scoped.
// 1. GLOBAL SCOPE
// This variable is declared at the top level. It can be accessed anywhere.
const globalUsername = "Alice";
function userProfile() {
console.log("Global inside function:", globalUsername); // Works! ✅
}
userProfile();
console.log("Global outside function:", globalUsername); // Works! ✅
// 2. BLOCK SCOPE
// Curly braces define the boundaries of a block.
if (true) {
// These variables only live inside this 'if' block
let blockBonus = 500;
const blockCode = "SAVE20";
console.log("Inside block:", blockBonus); // Works! ✅
}
// Trying to access block-scoped variables outside their block will fail
console.log(blockBonus); // ❌ Throws ReferenceError: blockBonus is not defined
References
https://www.geeksforgeeks.org/javascript/switch-case-in-javascript/
https://intellipaat.com/blog/switch-statement-javascript/
https://www.greatfrontend.com/questions/quiz/explain-the-difference-between-global-scope-function-scope-and-block-scope

Top comments (0)