javascript / beginner
Snippet
The Switch Statement for Multiple Conditions
The switch statement evaluates an expression and executes code blocks based on matching case labels. It is often cleaner than multiple if-else statements.
snippet.js
1
2
3
4
5
6
7
8
function getTrafficLight(color) {switch (color) {case 'red': return 'Stop';case 'yellow': return 'Caution';case 'green': return 'Go';default: return 'Unknown';}}
react
Breakdown
1
switch (color) {
Starts the evaluation based on the value of the variable 'color'.
2
case 'red': return 'Stop';
If color is exactly 'red', the function returns 'Stop'.
3
default: return 'Unknown';
The fallback code that runs if no cases match the input.