Problem with ++ operator after expression

Viewed 86

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.

4 Answers

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).

++ 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","")))++

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);

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);

Related