-2

I am extremely new to JS and wanted to try the following.

var dev=4;
console.log(dev++);

I expected the output to be 5, but the output was 4. Can not understand the reason.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Heisenberg
  • 63
  • 9
  • 6
    x++ is post increment, the increment is done after the value is "read" - think of it as read and return x, then add 1 - ie increment "post" access – Bravo Aug 28 '21 at 15:31
  • ^^ and if you did want to see 5 in your example, you'd use the *pre* version: `++dev`, which means "increment it, then read the result and use it". If the `++` (or `--`) is *before* the operand (`dev`), the increment (or decrement) is done before the read; if it's after, it's done after. – T.J. Crowder Aug 28 '21 at 15:35
  • 1
    See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Aug 28 '21 at 15:36
  • use `console.log(++dev)` – Mister Jojo Aug 28 '21 at 15:36

2 Answers2

2

dev++ returns dev, then adds one to it

++dev adds one to it, then returns it (your goal)

Erfan
  • 1,725
  • 1
  • 4
  • 12
0

x++ first uses the current value, then increments its value.

++x first increments its value, then uses the value of the variable. This is the notation you're probably after.

Pieterjan
  • 2,738
  • 4
  • 28
  • 55