0

I have checked the other Q/As. Mine is a bit different and I'm new to ReactJS.

Following code for setting const variable evaluates 0 as false/undefined and value returned from myFunc is "" :

function formatAmount(x){
  if(x === undefined || x === null) return "";
  return(x.toLocaleString("en-US",{style: "currency", currency: "USD"}));
}
//When user.bill.amount == 0 this line evaluates it to false!!
const amount = user?.bill?.amount || user?.statement?.amount;

function myFunc(){
  return(formatAmount(amount));
}

I tried expanding it with a function and IF conditions but the value returned by myFunc is "$NaN":

const amount = () => {
  if(user?.bill?.amount || user?.bill?.amount === 0){
    return user?.bill?.amount;
  }
  if(user?.statement?.amount || user?.statement?.amount === 0){
    return user?.statement?.amount;
  }
}

Expected:

When user.bill.amount == 0, myFunc should return "$0.00"

Actual:

myFunc returns empty string when user.bill.amount == 0

3
  • And your question is...? Commented Jul 17, 2020 at 22:43
  • @Lenin Raj Rajasekaran, My question is how do I get myFunc to return "$0" when user.bill.amount == 0. I will edit the question, thanks for the feedback! Commented Jul 17, 2020 at 22:49
  • 1
    typo in toLocalString -> .toLocaleString Commented Jul 17, 2020 at 23:07

1 Answer 1

2

I think the problem here is 0 is falsy so when using || operator 0 will evaluate to false.

const amount = user?.bill?.amount || user?.statement?.amount;

If your environment supports the nullish operator that would work here.

const amount = user?.bill?.amount ?? user?.statement?.amount;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.