Search code examples
javascriptprefix-operator

Why can't I use the prefix operator in front of a function call?


When I run ++this.get('votes'), I get the following error message

Uncaught ReferenceError: Invalid left-hand side expression in prefix operation.

I got the same error message with ++(this.get('votes')).

I was able to fix the problem with this.get('votes') + 1 but I can't figure out why the prefix operator doesn't work.

Why shouldn't this.get('votes') evaluate to 0 and then become 1 and return the value 1?


Original code in context:

var Comment = Backbone.Model.extend({
  initialize: function(message) {
     this.set({votes: 0, message: message});
  },
  upvote: function(){
    // Set the `votes` attribute to the current vote count plus one.
    this.set('votes', ++this.get('votes')); 
  }
}
var comment = new Comment('This is a message');
comment.upvote();

Solution

  • The underlying problem is that you can't assign to this.get('votes'); i.e, something of the form:

    f() = x;
    

    is not valid because f() isn't an lvalue.

    If you check the specs, you'll see that ++x is roughly the same as:

    x = x + 1
    

    and you can't assign a value to a function call. You're really trying to say:

    this.get('votes') = this.get('votes') + 1;
    

    and that's not JavaScript.