-4

Curious case in JavaScript where you get not exactly the most people would expect

function test() {
  var v = 2;
  var v = v++;
  console.log(v);
}
test();

Why the ++ seems ignored here? at what point the ++ operation is executed?

"v++ increments v to 3 and returns 2" what is the first, increment or return?

  • if it increments first, the returned value should be "3"
  • if it returns first 2, then after that increments, so the incremented value is 2 and v should be 3...
serge
  • 13,940
  • 35
  • 121
  • 205
  • It's called a [postfix increment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#postfix_increment). It will assign and then increment. With `a = 0; b = a++;`, `a` will be 1 and `b` will be 0. – evolutionxbox May 05 '22 at 14:54
  • @evolutionxbox thanks, I am aware, but here is rather interesting at what point is created the new variable – serge May 05 '22 at 14:55
  • The second `var` is ignored. – Pointy May 05 '22 at 14:55
  • @Pointy not at all – serge May 05 '22 at 14:56
  • If you used `let` you would get a syntax error. – evolutionxbox May 05 '22 at 14:56
  • @evolutionxbox but we don't use here let ) – serge May 05 '22 at 14:56
  • Yes, the second **declaration** is ignored, as the variable `v` was already declared in that scope. The *initialization* is not ignored, but the declaration is. – Pointy May 05 '22 at 14:56
  • `var v = v++;` can be replaced with `v = v++;` without changing the behavior and result, if this helps you understanding the code. There is no _"the creation of the new "v""_. – jabaa May 05 '22 at 14:57
  • at what point the `++` does work then? because it has any effect – serge May 05 '22 at 14:59
  • 2
    `v` is initialized with `2`. `v++` increments `v` to `3` and returns `2`. `var v = v++;` assigns `2` to `v`. – jabaa May 05 '22 at 15:00
  • 1
    The language specification says that the left-hand side is evaluated first, and then the right-hand side value is assigned to the left-hand side. The value of `v++` is the original value of `v`, so `v` ends up being 2. – Pointy May 05 '22 at 15:00
  • I think in C and C++ such an expression might be explicitly undefined, so the runtime/compilation could do whatever it wants. In JavaScript, however, the behavior is explicitly defined. – Pointy May 05 '22 at 15:01

1 Answers1

1
  • v is initialized with 2.
  • The expression v++ increments v to 3 and then returns 2.
  • The statement var v = v++; assigns 2 to v (overwrites the 3 in v with the 2 returned from v++).
  • console.log(v) prints 2
jabaa
  • 5,844
  • 3
  • 9
  • 30