Conditional Statements: Part 3
Rahul Raj
Posted on June 6, 2022
Still we can improve our conditional statements. How?
Checking the conditions and returning the response at the same time.
// Legacy conditional statement
function getDesignation(designation?: number): string {
let designationInString: string;
if (designation === undefined) {
designationInString = "";
} else if (designation === 1) {
designationInString = "Dev";
} else if (designation === 2) {
designationInString = "QA";
} else if (designation === 3) {
designationInString = "Analyst";
} else {
designationInString = "";
}
return designationInString;
}
But we can do better than this now.
// New conditional statement
function getDesignation(designation?: number): string {
const designationList: {[key:number]: string} = {
1: "Dev",
2: "QA",
3: "Analyst",
};
// Always check for the non valid conditions first
if (!designation) return "";
return designationList[designation] || "";
}
In this way we can even have our designationList
outside the function and get the desired designation.
If you like the post follow me for more
💖 💪 🙅 🚩
Rahul Raj
Posted on June 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.