M
M
Marik Zukor2016-02-08 12:55:37
JavaScript
Marik Zukor, 2016-02-08 12:55:37

How does the decrement operator work in JS?

The operator, increment is quite clear. ++n will first increase the value by one and then return that value. n++ is the opposite. But what about the decrement operator? Why does it work the other way around?
Example:

var n;
for(n = 10; --n;) {
  console.log(n);
}

In this example, the for statement will run up to 1, even though --n must first decrement the value by 1 and then return it. if you change it to n--, then the console will show up to zero, although n-- first returns the value, and then decreases it. Explain, please, what's the matter? I do not quite understand, everything is clear with the increment.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GreatRash, 2016-02-08
@BeriaFantom

Because you seem to have a poor idea of ​​how the for loop works. It will work as long as --n === true . In the case of --n , there will immediately be 0, i.e. false and the loop will stop, so you will never see zero. In the case of n-- , there will still be one and the loop will continue, and at the time the log is called, n will already become zero.

// последняя итерация цикла

for (n = 10; --n;) { // n === 0
  console.log(n); // сюда не зайдёт ибо 0 == false
}

for (n = 10; n--;) { // n === 1
  console.log(n); // а вот тут уже n === 0
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question