dev-resources.site
for different kinds of informations.
Avoid Else Statement In Your Function To Write a Clean Code
When I took programming class in college, one of fundamental topic is control flow, including if - else if - else
statement.
if (a === 'one') {
// do something here
} else if (a === 'two'){
// do something here
} else {
// I said, do something!!
}
My lecturer taught me in a good way how to write and implement if statement. But I just remembered, I learn if statement
subject before I learn about function.
It is okay if we use else
outside function or in top level code, moreover we are still need else
.
const sayHi = true;
if (sayHi) {
console.log("Hi!")
} else {
console.log("....")
}
In a function that returned something, in most cases we don't even need the else statment. Here is the example.
function func(isRich: boolean){
if (isRich) {
return "I am rich!";
} else {
return "Can you give me a money, please?";
}
}
Since function will stop executing lines of code after return
is written, we can just remove else statement.
function func(isRich: boolean){
if (isRich) {
return "I am rich!";
}
// intepreter, compiler, or anything won't execute codes bellow
return "Can you give me a money, please?";
}
When we need to check another condition that has been specified we might use else if
statement and write the logic inside the block.
function grade(score: number) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
};
Or we can write it with switch-case
.
function grade(score: number){
switch (true) {
case score >= 90:
return 'A';
case score >= 80:
return 'B';
case score >= 70:
return 'C';
case score >= 60:
return 'D';
default:
return 'F';
}
};
Two examples above work fine. But I prefer this style.
function grade(score: number){
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
};
Thank you for reading!
Featured ones: