Search code examples
javascriptnumbersincrementliteralsdecrement

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?


Solution

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