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!
Oldest comments (5)
Personally for me, I like the switch statement. Multiple else if statements just doesn't sit comfortably with me.
Greetings from ECMAScript Pattern Matching
Thank you for new insight!
That's new for me.
This week they'll decide whether it gets to stage 2 (as an ES feature). It's been lingering in stage 1 for the past 4 years.
As I'm expression oriented anyway, I'm perfectly happy with
but that rubs many people the wrong way 🤷
Thanks for sharing article, I prefer the last style without else. That's my personal opinion. But as @peerreynders mentioned about ECMA Script Pattern Matching, it's a wow for me. Will give it a try for sure.