There are 3 values,
previousBalanceTotal
= It is the total balance in a bank accountpreviousWithdrawTotal
= I've withdrawn this much total value beforenewWithdrawAmount
= 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);
CodePudding user response:
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);
CodePudding user response:
Try this code block
const newWithdrawAmount = 13000;
const previousBalanceTotal = 12000;
const previousWithdrawTotal = 300;
var newWithdrawTotal;
function calc() {
if(newWithdrawAmount < previousBalanceTotal) {
return newWithdrawTotal = newWithdrawAmount previousWithdrawTotal
} else {
console.log(previousWithdrawTotal);
alert('you can not withdraw more than your balance');
return newWithdrawTotal = previousWithdrawTotal;
}
}
calc()
console.log(newWithdrawTotal);