Hello there!
I wrote this for a web shop I’m trying to create. I understand that this is very simple and that it needs work.
My issue is that I can not make it NOT go into a negative if the balance is below 0.
S
If the price is 400, the balance is 200, the voucher discounts 100… it will say succes and that the balance is -100.
So my questions…
- How can I stop it from going into a negative?
- Any tips how to optimize and make this code better?
Thank you!
var total = 400;
var balance = 1100;
var voucher = 100;
if ( (total > balance) || (balance < 0) ) {
console.log("Insufficient funds. The total is " + total + "$ and you only have a balance of " + balance + "$.");
} else if (voucher > 0 && total > balance); {
total = total - voucher;
console.log(voucher + "$ Voucher applied. The new total is " + total + "$.");
}
if (total < balance) {
console.log("Sufficient funds. Success! You have a new balance of " + (balance - total) + "$.");
balance = balance - voucher - total;
} else if (balance < 0); {
console.log("ERROR");
}