Conditional Statements: Part 3

rahulrajrd

Rahul Raj

Posted on June 6, 2022

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

💖 💪 🙅 🚩
rahulrajrd
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.

Related

How to Learn TypeScript in One Day?
javascript How to Learn TypeScript in One Day?

November 6, 2024

How to configure JSDoc instead of TypeScript
Conditional Statements: Part 3
javascript Conditional Statements: Part 3

June 6, 2022

Conditional Statements: Part 2
javascript Conditional Statements: Part 2

March 22, 2022