1

I am trying to redo the delphi example to js. Two cycles. The first is “repeat until”. The second is “do while”. If you specify in delphi the conditions where the comparison takes place by digit, then if it matches, the cycle will be triggered once, if not, then repeatedly. In js, I try to do the same, it happens the other way around, if there is a match, then multiple repetitions, if there is no match, then once. Why is this happening and how to fix it? Delphi:

procedure TForm1.FormCreate(Sender: TObject);
var i:integer;
begin
 repeat
          i := 1;
          ShowMessage(IntToStr(i));
 until (i = 0) or (i = 4);
end;

js:

var i;
do
{
   i = 1;
   alert(i);
}while(i == 0 || i == 4)
2
  • 1
    Your Delphi loop is a bit "strange": You will only get an infinite number of 1 messages! The JS loop will give you exactly one such message. Commented Jan 21, 2021 at 9:39
  • To expand on Andreas's comment, you are not changing i in either loop. You must do that (probably by incrementing) in both cases to get a sensible action. Commented Jan 21, 2021 at 12:24

1 Answer 1

1

"Until" and "while" have a very different meaning in the English language, and in programming. As a matter of fact, "until A" means "while not A".

Therefore, you need to invert the while condition in JavaScript.

let i;
do {
   i = 1;
   alert(i);
} while(!(i == 0 || i == 4));

Of course, you could simplify the while condition by applying Boolean algebra, or more specifically De Morgan's Law. Also note, that I allowed myself to replace var with more modern let.

Sign up to request clarification or add additional context in comments.

5 Comments

Might be educational to mention De Morgan here.
@AndreasRejbrand I’ve updated my answer to include that. Applying De Morgan is left as an exercise, though ;)
Also (at least in Delphi) do...until always executes at least once. This is not true of while...do, so it is not quite true to imply that they are equivalent if you invert the conditions.
@Dsm Of course, do-while always executes the statement at least once. Please see here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. Please note that JavaScript (like most C related languages) has do-while and while, which do different things.
@Dsm: idmean is comparing Delphi repeat..until and JS do..while and they both do at least one iteration, so there is no difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.