-3

Both of the consolt results are same. Anyone can explain me why it is being like that?

console result

for (let index = 0; index < 5; index++) {
  console.log(index)
}
for (let index = 0; index < 5; ++index) {
  console.log(index)
}
ozan kurucu
  • 1
  • 1
  • 3
  • 2
    Which difference did you expect? – sp00m Oct 22 '21 at 14:49
  • Its work same, because index++ will increment after initialization and ++index will increment first then initialize, you are not initializing there you just incrementing. – Bharat Oct 22 '21 at 14:52
  • The second result should be 1,2,3,4 – ozan kurucu Oct 22 '21 at 14:54
  • @ozankurucu They should both be the same because both snippets start with `index = 0` before the first iteration. Both snippets check `index < 5` before each iteration. and both snippets increment `index` at the end of each iteration. The only difference between the snippets is between pre- and post- increment, however this difference is irrelevant to the flow of a `for`-loop because this difference only affects the increment expression itself (i.e. `++index` / `index++` -- the `for`-loop does not use the result of these expressions; the result is thrown away). – Ben Cottrell Oct 22 '21 at 14:56
  • @ozankurucu let index = 0 will execute then it goes into loop, not it will increment first – Bharat Oct 22 '21 at 14:57
  • @BenCotrell Actually, for loop using the result of ++index/index++ because of both log are 0,1,2,3,4. Do you know why the first result of ++index is thrown away? – ozan kurucu Oct 23 '21 at 18:00

1 Answers1

0

First loop use post, and second loop use pre increment. The desc like this ++index (pre-increment) means "increment the variable; the value of the expression is the final value" Index++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"

Or u can follow this link https://stackoverflow.com/a/3469896/17123841