3

I get the following error when trying to increment a value obtained from a map in the console in Chrome (50.0.2661.86):

Uncaught ReferenceError: Invalid left-hand side expression in postfix operation(…)

And similar in Node (4.4.3):

ReferenceError: Invalid left-hand side expression in postfix operation
    at repl:1:3
    at REPLServer.defaultEval (repl.js:262:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:431:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)
    at REPLServer.Interface._ttyWrite (readline.js:827:14)

The offending code is:

var m = new Map()
m.set(1, 0)
m.get(1)
var n = m.get(1)++ // Uncaught ReferenceError: Invalid left-hand side expression in postfix operation(…)

The following also fail:

var n = ++m.get(1)
var n = ++(m.get(1))

A bug in V8 maybe? Or a misunderstanding in what's happening syntax-wise with the ++ operator?

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40

2 Answers2

4

I'm not an expert in JS evaluation scheme, but here's my try at explaining that.

In JS, (1)++ is invalid; you can't change a value. What you can do is change a value attribution to a name:

var a = 1;
a++;

In this case the value of 1 doesn't change; what changes is that a now points to a different value.

Similarly, you can't increment a value returned by .get(); you need to convert it to a named expression before you can change that.

In C++ terms we would say that ++ needs an lvalue, but the function return is an rvalue.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
3

You can't assign a value to a function call. That would be like saying

m.get(1) = m.get(1) + 1

You need to split this into two statements:

const n = m.get(1) + 1;
m.set(1, n);

Or:

const n = m.get(1);
m.set(1, n++);
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176