Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question