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
Top comments (0)