Simple solution to hardy error?


#1

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…

  1. How can I stop it from going into a negative?
  2. 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");
}

#2

You have a semicolon in there after your else-if condition for starters. I’m sure that cancels out the code block and probably puts it outside the if statement.


#3

As @lee8oi mentioned, you have these weird constructs:

} else if (...); {

There is no ; after that ) you need to write:

} else if (...) {

Also, when you post code you can do this:

```
console.log("I am code.");
```