3

so I have this javascript code:

let version = "v179";
version = (parseInt(version.replace("v","")))++;
console.log("got:",version);

but I get this error: Uncaught ReferenceError: Invalid left-hand side expression in postfix operation. However it works if I replace the ++ with + 1 any idea why it does that? Why can't I use the increment operator for that?

Thanks in advance.

Alex
  • 840
  • 7
  • 23
  • Polemics here: https://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript best answer said: "My view is to always use ++ and -- by themselves on a single line" – GrafiCode Mar 25 '20 at 11:57

4 Answers4

11

foo++ means "Take the value of foo, add 1, then assign it back to foo.

parseInt(version.replace("v","")) gives you 179, so you are saying:

179++ which means "Take the value of 179" (hang on, 179 is a value, not something that has a value), "add 1 to it and then assign it back to 179".

So you're trying to say 179=180 which doesn't make sense. You have to assign to a variable (or object property).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Oh yeah, I see I have forgotten the basics! Thank you! Accepting your post as answer in 8 minutes – Alex Mar 25 '20 at 11:58
3

++ only works on lvalues, as it changes the content of a variable. It is roughly (but not completely) equal to += 1, not + 1. Just like how it's meaningless to write

(parseInt(version.replace("v",""))) += 1

or

(parseInt(version.replace("v",""))) = 17

it also makes no sense to write

(parseInt(version.replace("v","")))++
Amadan
  • 191,408
  • 23
  • 240
  • 301
2

Literally you trying to do next -

179++

Incremental function will not work that way. the only way to do it -

let version = "v179";
version = parseInt(version.replace("v",""));
version++;
console.log("got:",version);
Reidenshi
  • 180
  • 8
1

The code x++ means that increase the value of the variable x 1. Its same as

x = x + 1;
x += 1;

Now (parseInt(version.replace("v",""))) will return a value like 179. So it doesn't make sense to increase it. ++ or -- is only for variables not for constant values.

You should use + 1 to add one to a constant value

let version = "v179";
version = (parseInt(version.replace("v","")))+ 1;
console.log("got:",version);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73