JavaScript conditional statements allow your code to make decisions. Switch statements evaluate a single expression against multiple possible values to execute specific blocks of code, while the ternary operator acts as a concise, one-line shorthand for a standardif...else statement.
1. Switch Statements
A switch statement is ideal when you have one variable being compared to many strict equality (===) conditions. Using break prevents the code from falling through to the next case.
**
Switch Control Flow
**
Based on a condition, switchselects one or more** code blocks to be executed.**
switchexecutes the code blocks that matches an expression.
switch is often used as a more readable alternative to many if...else if...else statements, especially when dealing with multiple possible values.
This is how it works:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, no code is executed.
**
## Example
**
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
const role = "admin";
let accessLevel;
switch (role) {
case "user":
accessLevel = "Standard read access";
break;
case "editor":
accessLevel = "Read and write access";
break;
case "admin":
accessLevel = "Full system access";
break;
default:
accessLevel = "No access granted";
}
console.log(accessLevel);
// Output: Full system access
2. Ternary Operator
The ternary operator is written as condition ? expressionIfTrue :expressionIfFalse. It is highly efficient for quick variable assignments or simple inline checks.
const isMember = true;
const discount = isMember ? 0.20 : 0.00;
console.log(`Your discount is ${discount * 100}%`);
// Output: Your discount is 20%
You can even nest ternary operators for multiple checks, though doing so can affect readability:
const score = 85;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
**
The break Keyword
When JavaScript reaches a break keyword, it** breaks out of the switch block.**
This will **stop the execution **inside the switch block.
No more statements in the switch block will be executed.
It is not necessary to break the last case. The switch ends (breaks) there anyway.
`
**`The break keyword is crucial for preventing a "fall-through."
Without break, the code will continue to execute the next case blocks (and the default block if present) even if their values do not match the expression.**
**
Top comments (0)