An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
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 that if statement 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!
Original Link: https://dev.to/estotriramdani/avoid-else-statement-in-your-function-to-write-a-clean-code-1l85
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To