trevor trevor - 1 month ago 17
Javascript Question

Why is the variable "a" in this JavaScript statement not a variable expression?

In "Up & Going", the first book in Kyle Simpson's "You Don't Know JS" series, he presents the following statement, and explains that it contains four expressions:

a = b * 2;

He says that:

  • 2 is a literal value expression

  • b is a variable expression

  • b * 2 is an arithmetic expression

  • a = b * 2 is an assignment expression

All of which I agree with.

The Mozilla Developer Network defines an expression as any valid unit of code that resolves to a value.

Is a not a variable expression because it is a LHS expression and being assigned to rather than evaluated?


Informally, an expression is something which conforms to the syntax for an expression, and is treated as an expression because it appears in an expression context. It is evaluated and results in a value.

For instance, {} is an expression indicating an empty object literal only in expression contexts; elsewhere it might be a block. The same holds for a syntactic construct starting with the function keyword.

In contrast, we normally don't think of the left hand side of assignments as being an "expression". Certainly, we could not write a + 2 = 3. Even when the left side could be considered an expression, such as a or a.b, we normally don't refer to it as an expression, because we think of expressions as being things that are evaluated, whereas such left hand sides are "references".

It is this common usage that the author of your book is following in not identifying a as an expression in a = b * 2.

However, the terminological waters are muddied somewhat by the names of the tokens used in the spec. The spec defines something called an AssignmentExpression, which is basically any expression like 2 or a or a + 2 or a = b (which evaluates to b). So far so good. But it then proceeds to define something called LeftHandSideExpression, which obviously is what occurs on the left-hand side of an assignment (or to which ++ etc. is applied), but defines it as an AssignmentExpression. What? We can't put a 2 on the left-hand side, can we? The spec addresses this by limiting what kinds of AssignmentExpressions can serve as LeftHandSideExpressions, excluding 2, for example (since it is not a "IsValidSimpleAssignmentTarget").

So it is correct to not call the a in a = b * 2 an expression--in the common usage of the term "expression". But it is also technically correct to say that it is an expression, in the sense that that word is used in the spec, where it is a LeftHandSideExpression.