Putting an operator inside of alert() in javascript

Viewed 85

I'm going through a loops tutorial on javascript.info and I'm confused why the following happens:

let i = 3;
while (i) alert(i--);

result: 3, 2, and 1

Why is the first result 3 and not 2?

Thanks.

2 Answers

You are using the Decrement (--) operator

This is what MDN docs say

If used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.

If used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing.

What you see is the value before decrementing, thats how it works. If you want the other way use --i

The -- operators work 2 different ways.

The following code will decrease by 1 after it runs through:

let i = 3;
while (i) alert(i--); //3

The following code will decrease by 1 before it runs through:

let i = 3;
while (i) alert(--i); //2

I would also suggest doing this in the loop rather than the alert.

Example:

let i = 3;
while (--i >= 0) alert(i); //2
Related