-1

I am practicing while loop and below is code

PHONE_PRICE = 90; 
bank_balance = 303.91; 
amount = 0;
while (amount < bank_balance) {    
  amount = amount + PHONE_PRICE;
}
console.log("Your purchase: " + amount); 

Now I understand after each iteration it is checking the condition and running the next iteration. I am trying to stop the next iteration if condition is going to be false. I have tried with do while loop as well however it gives the same behavior.

Here I am not trying to loop thru an array.... however trying to stop the iteration if condition is going to be false. Let me know if its same as loop thru an array in anyway

Taha Sk
  • 67
  • 1
  • 7
  • 1
    Possible duplicate of [Loop through array in JavaScript](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript) – The Reason Apr 27 '16 at 12:34
  • 1
    I recommend you creating new variables using the `var` keyword, and not just assigning them like you're doing here. [Here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var) is a link if you're interested. – Fredrik Apr 27 '16 at 12:40
  • 1
    Took note of that @FredrikA. Thanks – Taha Sk Apr 27 '16 at 12:59
  • If you want to do the addition a bit more terse, you could also use the `+=` operator. With that, you could write `amount += PHONE_PRICE` instead of `amount = amount + PHONE_PRICE` :) – Fredrik Apr 27 '16 at 13:02

1 Answers1

3

I am trying to stop the next iteration if condition is going to be false

If you want to only increase the amount if it won't exceeed the balance, then try

while ((amount + PHONE_PRICE) < bank_balance) {    
  amount = amount + PHONE_PRICE;
}

This will ensure that amount won't exceed 270 (3 iterations of 90).

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Either this, or you could simply do the incremenation and if-statement in the loop. `amount += PHONE_PRICE;` and `if (... > ...) break;`. – Fredrik Apr 27 '16 at 12:38