0

I have a doubt about using while i-- and while -ii in code.

ar points = [30,100];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
   var len = arr.length;
   var max = -Infinity;
   while (len--) {
  if (arr[len] > max) {
    max = arr[len];
  }
}
return max;
}

In the above code, since len is 2, I am guessing the len value becomes 1 in the initial iteration involving the if statement. After this iteration, in the while (len--) , does len become 0 or 1? Judging from this, it seems the arr[2] never gets evaluated.

And what difference will the code make if while --len was used instead? Thank you.

Kwaku Biney
  • 327
  • 1
  • 3
  • 11
  • There is no value at `arr[2]`. What you mean by `arr[2]` this is actually `arr[1]`. – Sajeeb Ahamed Nov 01 '20 at 10:16
  • `var len = arr.length;` -> `len = 2`; `len--` -> `len = 1`; `arr[len]` -> `arr[1]`; `len--` -> `len = 0`; `arr[len]` -> `arr[0]`. Loop terminates. If the condition was `--len` then the last iteration would be skipped. – VLAZ Nov 01 '20 at 10:17
  • Isn’t the an almost a never ending loop? – evolutionxbox Nov 01 '20 at 10:18
  • *"Judging from this, it seems the `arr[2]` never gets evaluated."* Correct, which is good because you don't have any value there. `len--` vs. `--len` doesn't make any difference to the code in the loop body, it just changes when the loop ends, because `while (len--)` will stop when the value of `len` is `0` **before** the decrement, but `while (--len)` will stop when the value of `len` is `0` **after** the decrement. For the above you want what you have, so that you get two loop iterations (one when `len` has just gone from `2` to 1` and another when `len` has just gone from `1` to `0`). – T.J. Crowder Nov 01 '20 at 10:19
  • @T.J.Crowder So if `1` is being used as `len` in the code body, when it's time to perform the `while (--len)` check, the while check uses `1` and become `0` post decrement and the loop will end? Why does that happen? – Kwaku Biney Nov 01 '20 at 10:40
  • @kweks45 - `while (--len)` means "decrement `len` and then, afterward, if the value is truthy, run the loop body with that new value." So if `len` is `2` to start with, and you use `while (--len)`, `--len` changes `2` to `1` and then checks to see if `1` is truthy. It is, so the loop body runs with `len === 1`. Then it's time for the next loop. `--len` changes `1` to `0` then checks to see if the new value, `0`, is truthy. It isn't, so the loop body isn't executed. That's why you want `while (len--)` for the above. – T.J. Crowder Nov 01 '20 at 10:51
  • @kweks45 - Put another way: `len--` means "grab the value, then decrement the variable." But `--len` means "decrement the variable, **then** grab the [new] value." – T.J. Crowder Nov 01 '20 at 10:52
  • @T.J.Crowder Got it! Thanks! – Kwaku Biney Nov 01 '20 at 10:55

0 Answers0