Switch Statements to Object Literals
More natural control of flow in JavaScript β¨
Hey everyone! π
This is UltiRequiem here. I'm a 15-year-old, Peruvian π΅πͺ, full-stack and system developer, with the intention to become a successful Software Engineer.
Today I will explain the problems with the switch
statement in JavaScript and
my personal solution, object literals β¨
What is the Switch Statement?
The switch statement is used to perform different actions based on different conditions.
"The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value."
-- > MDN Web Docs
Let's look at this example π
const expr = "Papayas";
switch (expr) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Mangoes":
case "Papayas":
console.log("Mangoes and papayas are $2.79 a pound.");
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}
// expected output: "Mangoes and papayas are $2.79 a pound."
Itβs similar to if
and else
statements, but it should evaluate a single
value - inside the switch
we use a case to evaluate against each value.
Something is probably wrong when you start seeing a lot of else
and if
statements, and in most cases you should use something like switch
because it
is better suited for the intended use.
Hereβs some else
and if
abuse π
function permissionLeve(user) {
if (user.type === "administrator") {
return 3;
} else if (user.type === "helper") {
return 2;
} else if (user.type === "user") {
return 1;
} else {
return 0;
}
}
Problems with switch
- Non-standard look
The rest of JavaScript uses curly braces yet switch
does not.
break
Weβre forced to manually add break
statements within each case, which can lead
to difficult debugging and nested errors further down the case should we forget.
- Big O notation:
O(n)
Although this should not be a problem unless you work with huge inputs, it is important to mention it.
Object Literals
We can implement the previous function using an Object literal as follows π
function permissionLeve(user) {
const permissions = { administrator: 3, helper: 2, user: 1 };
return permissions[user.type] ?? 0;
}
We saved a few lines of code and overall is more readable.
In cases where more complex things need to be done, we can also store functions inside an object literal π
function makeFood(user) {
const foodMakers = {
administrator() {
makePizza();
},
helper() {
makeSandwich();
},
user() {
makeApple();
},
};
return foodMakers[user.type]();
}
More maintainable and readable.
We also donβt have to worry about break
statements and cases falling through -
itβs just a plain Object.
Object literal fall-through
With switch
cases, we can let them fall through (which means more than one
case
can apply to a specific piece of code).
"You can use the
break
statement within a switch statement's body to break out early, often when all statements between twocase
clauses have been executed. Execution will continue at the first statement followingswitch
.If
break
is omitted, execution will proceed to the nextcase
clause, even to thedefault
clause, regardless of whether the value of that clause matches.-- > MDN Web Docs
Example π
const type = 'coke';
let snack;
switch(type) {
case 'coke':
case 'pepsi':
snack = 'Drink';
break;
case 'cookies':
case 'crisps':
snack = 'Food';
break;
default:
drink = 'Unknown type!';
}
console.log(snack); // 'Drink'
Doing this for Object Literals is simpler and more declarative - as well as being less prone to error. Our code suddenly becomes much more structured, readable, and reusable π
function snack(type) {
let snack;
function isDrink() {
snack = "Drink";
}
function isFood() {
snack = "Food";
}
const snacks = {
coke: isDrink,
pepsi: isDrink,
cookies: isFood,
crisps: isFood,
};
return snacks[type]();
}
Summing Up
Object literals are a more natural control of flow in JavaScript, switch
is a
bit clunky and prone to difficult debugging errors.
Objects are more extensible, and maintainable, and we can test them a lot better.
I have been preferring to use Object literals over a switch
for some time, did
this article convince you to do the same? π§
Cheers π«