DEV Community

Cover image for Step up your typescript game with these operators
amanbhoria
amanbhoria

Posted on • Edited on

3

Step up your typescript game with these operators

  • Nullish Coalescing Operator (??)

The ?? operator is used to provide a default value when dealing with null or undefined. It checks if the left-hand side is either null or undefined, and if it is, it returns the right-hand side value.

let value = null;
let defaultValue = "DefaultValue";

let result = value ?? defaultValue;
console.log(result); 
// Output: DefaultValue
Enter fullscreen mode Exit fullscreen mode
  • Safe assignment operator (?=) [Proposed]

The Safe Assignment Operator (?=) is a simple solution for error handling. Instead of wrapping code in complex try/catch blocks, ?= allows you to handle errors directly within assignments, making your code easier to read and manage.

try {
  const result = errorCausingFunction();
  // More logic with result
} catch (error) {
  console.error('An error occurred:', error);
}
Enter fullscreen mode Exit fullscreen mode

Now you can handle this try/catch block in one line

const result ?= errorCausingFunction();
Enter fullscreen mode Exit fullscreen mode
  • Double Exclamation Mark (!!)

The !! operator is a trick used to convert a value to a boolean (true or false). This is useful when you want to check if a value is truthy or falsy.

Step up your validation game using this operator

let value = ''

// Basic Approach
if (value === null || value === undefined || value === '') {
  console.log("Value is null, undefined, or an empty string");
} 

// Advanced Approach
if(!!value) {
  console.log("Value is null, undefined, or an empty string");
}
Enter fullscreen mode Exit fullscreen mode

Keep building!

Sentry blog image

The Visual Studio App Center’s retiring

But sadly….you’re not. See how to make the switch to Sentry for all your crash reporting needs.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post