javascriptsyntaxassignment-operator

Why is assigning to a function call expression valid syntax?


In another question, someone had an incorrect class definition that included code like:

var myClass = function() {
  /* ... */
  this.name() = function() { /* ... */ };
}

The obvious error is that the method should be defined with this.name = ..., without the parentheses after name. When you call the constructor, you get an error because this.name is not defined. I created a simpler example in the console:

foo() = 3;      // Causes: ReferenceError: foo is not defined
function foo() {};
foo() = 3;      // Causes: ReferenceError: Invalid left-hand side in assignment

Is there any context where a function could return something that can be assigned to? I don't think JavaScript has references like C++ or PHP that can be assigned to. Why doesn't this cause a syntax error, rather than different errors depending on whether the function is defined or not?


Solution

  • Quoting from the ECMA Script 5.1 Specification for References,

    For example, the left-hand operand of an assignment is expected to produce a reference. The behaviour of assignment could, instead, be explained entirely in terms of a case analysis on the syntactic form of the left-hand operand of an assignment operator, but for one difficulty: function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference. (Another reason not to use a syntactic case analysis is that it would be lengthy and awkward, affecting many parts of the specification.)


    Is there any context where a function could return something that can be assigned to?

    So, no. No user-defined function could return a reference to which we can assign a value.

    Why doesn't this cause a syntax error, rather than different errors depending on whether the function is defined or not?

    As mentioned in the specification, the syntactic analysis would be lengthy, awkward and affecting many parts of the specification. So, the syntax check is not done.