Attila
Attila

Reputation: 1167

Why can't we increment (++) or decrement (--) number literals

For example, in the following JavaScript code, why do we not get errors when using variables, but when a number literal is used, I get an error (running on node v6.9.5)?

let x = 2;
console.log(x++); //2

let y = 2;
console.log(++y); //3

console.log(2++); //ReferenceError: Invalid left-hand side expression in postfix operation
console.log(++2); //ReferenceError: Invalid left-hand side expression in prefix operation

My understanding is that this doesn’t work because you can’t mutate the literal 2. In the previous example, you returned x or y (either before or after incrementing), so it was now equal to +1 its previous value (so x/ y now pointed to 3, rather than 2). However, you can’t increment 2 to be +1 its previous value and then have it point to the literal 3. 2 will always be 2, 2 will never point to 3.

Am I correct in my reasoning?

Upvotes: 0

Views: 1579

Answers (2)

Nico
Nico

Reputation: 1594

Literals are constants, and increment/decrement would try to change its argument respectively. But constant values cannot be changed.

It would be the same like coding something like

2 = 2 + 1;

Upvotes: 3

user149341
user149341

Reputation:

The argument of a increment/decrement operator must be a lvalue -- essentially, it has to be an expression that you could assign a value to. This can be either a variable, or certain types of simple structured expressions (like array[0]++ or object.foo++).

Constants aren't lvalues. You can't assign a value to them (3 = abc), nor can you mutate their values with the increment or decrement operators.

Upvotes: 0

Related Questions