Home > database >  Best practice conditional variable assignment in typescript
Best practice conditional variable assignment in typescript

Time:11-23

A very easy typescript question, which I need assistance with

Without using if statements, how would I conditional assign something to a constant variable

const myConstant = myProduct.productId;

I want it so that if the productId in myProduct is empty (""), it will assign the variable of myConstant to "No Product", I wish to do this without utilizing if statements.

Thanks

How would I go about doing this.

CodePudding user response:

This is how you could do it...

const myConstant = myProduct.productId || 'No Product';

Also, if you'd like to do null check for myProduct as well, you could put ? for it, like below

const myConstant = myProduct?.productId || 'No Product';

PS: this would work with empty strings, null, undefined and with 0.

CodePudding user response:

This will help you:

const myConstant = myProduct.productId || 'No Product';

This is called Short Circuit Evalution in JavaScript

Read more here : https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c

CodePudding user response:

You can try something like :

const myConstant = myProduct?.productId || 'No Product';

  • Related