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.
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
.
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
You can try something like:
const myConstant = myProduct?.productId || 'No Product';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.