DEV Community

Cover image for Conditional Statements: Part 3
Rahul Raj
Rahul Raj

Posted on

Conditional Statements: Part 3

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;
  }
Enter fullscreen mode Exit fullscreen mode

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] || "";
  }
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)