Avoid Check Null or Undefined In Typescript using Optional Chaining and Nullish Coalescing

Strengthen Typescript Code Legibility through Optional Chaining and Nullish Coalescing

TypeScript offers powerful features that make code more concise and efficient. Two such features, optional chaining and nullish coalescing, play a vital role in handling data effectively. In this article, we'll explore these features within the context of the NBA, showcasing their ability to simplify code and easily handle data. So, let's dive into the world of TypeScript and the NBA!

Optional Chaining: Safely Navigating NBA Player Data

Imagine you're working on an NBA statistics app and need to access player information. However, not all players have complete data available. To ensure smooth data handling, let's consider the example of accessing a player's team name using optional chaining:

const player = getPlayer();

Here, the getPlayer() function fetches player data from your data source. To access the player's team name, you might initially write code like this:

if (player !== undefined) {
  const team = player.team;
  if (team !== undefined) {
    const teamName = team.name;
  }
}

This approach is cautious but verbose. Thankfully, TypeScript offers a concise alternative with optional chaining:

const teamName = player?.team?.name;

The use of the question mark after each property ensures that the subsequent property is accessed only if its parent property exists. Optional chaining simplifies the code and saves you from writing multiple if statements, reducing the chances of encountering null or undefined errors.

Nullish Coalescing: Providing Default Values in NBA Data

Our NBA app encounters scenarios where certain player information may be missing. To handle these cases gracefully and provide default values, let's focus on accessing a player's jersey number using nullish coalescing:

const jerseyNumber = player.jerseyNumber !== undefined ? player.jerseyNumber : 0;

Here, we check if the jerseyNumber property exists in the player object. If it does, we use its value; otherwise, we provide a default value of 0. However, this can be simplified using nullish coalescing:

const jerseyNumber = player.jerseyNumber ?? 0;

The double question mark (??) checks if the left-hand side value is nullish (null or undefined) and provides the right-hand side value as the default if needed. Nullish coalescing ensures that we always have a valid jersey number, even if it's missing in the player data.

Conclusion:

Optional chaining and nullish coalescing are powerful features in TypeScript that greatly enhance data handling in NBA-related projects. By safely navigating data with optional chaining and providing default values using nullish coalescing, you can easily streamline your code, reduce errors, and create robust Typescript applications.

Happy coding!