Search code examples
javascriptfunctionreturnconditional-operator

How to use a function to set a value in a ternary operation?


There are 3 values,

  • previousBalanceTotal = It is the total balance in a bank account
  • previousWithdrawTotal = I've withdrawn this much total value before
  • newWithdrawAmount = The amount I want to withdraw now,

I need to set newWithdrawTotal now.

What i wanna do is, if my newWithdrawAmount is bigger than my previousBalanceTotal, I want to show an alert, and keep the newWithdrawTotal as previousWithdrawTotal, else add the newWithdrawAmount to previousWithdrawTotal and keep it in newWithdrawTotal.

I tried the following code, but it does not work when newWithdrawAmount is greater than previousBalanceTotal. It returns a function and doesn't show the alert. Could you please help me to solve this??

const newWithdrawTotal = (newWithdrawAmount < previousBalanceTotal) ? (newWithdrawAmount + previousWithdrawTotal) : function () {
    console.log(previousWithdrawTotal);

    alert('you can not withdraw more than your balance');
    return previousWithdrawTotal;
};
console.log(newWithdrawTotal);

Solution

  • You're not calling the function, you're just returning it. Use an IIFE to call the anonymous function immediately.

    const newWithdrawTotal = (newWithdrawAmount < previousBalanceTotal) ?
      (newWithdrawAmount + previousWithdrawTotal) : (function() {
        console.log(previousWithdrawTotal);
    
        alert('you can not withdraw more than your balance');
        return previousWithdrawTotal;
      })();
    console.log(newWithdrawTotal);

    You don't really need the function, you can use the comma-operator instead.

    const newWithdrawTotal = (newWithdrawAmount < previousBalanceTotal) ? (newWithdrawAmount + previousWithdrawTotal) : (
      console.log(previousWithdrawTotal),
      alert('you can not withdraw more than your balance'),
      previousWithdrawTotal
    );
    
    console.log(newWithdrawTotal);