"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Step up your typescript game with these operators

Step up your typescript game with these operators

Published on 2024-11-09
Browse:207

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
  • 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);
}

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

const result ?= errorCausingFunction();
  • 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");
}

Happy Coding!

Release Statement This article is reproduced at: https://dev.to/amanbhoria/step-up-your-typescript-game-with-these-operators-569a?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3