-5

Given this piece of code :

var n = 1;
console.log(n);
console.log(n--);
console.log(n);

The output is

1

1

0

And for this one

var n = 1;
console.log(n);
console.log(--n);
console.log(n);

The output is

1

0

0

What is happening?

Community
  • 1
  • 1
Luis Sieira
  • 29,926
  • 3
  • 31
  • 53
  • 2
    If you want it to be done before, use `--n` instead. – Etheryte Sep 14 '15 at 10:43
  • 7
    `n--` is not `--n` - and both variants work identically in javascript as they do in C/C++/C# and all the other spinoffs and variations – Jaromanda X Sep 14 '15 at 10:43
  • 1
    I thought the usual behavior of `n--` was to decrement `n` as the last operation on the line. Maybe you're thinking of `--n` which decrements right away. – Davide Sep 14 '15 at 10:44
  • @JaromandaX Strictly speaking, [C# does it differently to C](http://stackoverflow.com/a/3346729/50447) – Rowland Shaw Sep 14 '15 at 10:48

3 Answers3

6

If you want the value to update immediately you can move the -- to the front of the variable name:

var n = 1;
console.log(n);
console.log(--n);
console.log(n);

1

0

0

This is also how it works in C.

The decrement operator decrements (subtracts one from) its operand and returns a value.

  • If used postfix (for example, x--), then it returns the value before decrementing.
  • If used prefix (for example, --x), then it returns the value after decrementing.

MDN's notes on Arithmetic Operators

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • 3
    OP is asking if why this behavior is different from languages like `C`. If his assumption is wrong please mention it in your answer – Davide Sep 14 '15 at 10:46
4

First it's not only javascript who does this. All other programming languages including C, C++, PHP etc does the same. Check the following code:

var i = 1;
console.log(i) // Prints 1
console.log(i--) // It first prints the variable i then decrements it by 1. Therefore the result would be 1.
i = 1;
console.log(--i) // It FIRST decrements the variable i by 1 then prints its decremented value which prints the number 0
Zahid Saeed
  • 1,101
  • 1
  • 8
  • 14
1

There are two types of increment / dectement operators: prefix and postfix. Increment prefix adds 1 immediately, before the operand will be used in current code string operation. So n=++x will first increment x and then puts the incremented x to the n Increment postfix adds 1 after the value of the operand was used in current code string operation. So n = x++ will first puts x to n and then x will be incremented

Decrement operator acts identically

MysterX
  • 2,318
  • 1
  • 12
  • 11