Ben Aston
Ben Aston

Reputation: 55739

How are expressions evaluated?

The following code prints 6. This means that the variable x appears to have the value of both 3 (for the left x in the expression) and 2 (the result of the decrement).

let x = 3
console.log(x * --x) // 6 (NOT 4)

Does this work because before it is logically executed, the expression values are copied into a buffer as the expression is parsed according to associativity (here left-to-right)?

Likewise in this recursive factorial solution, the initial value of x is retained (for each time through factorial) after the recursive function call has returned, despite the decrement having occurred by that time.

function factorial(x) {
  if(!x) return 1
  return x * factorial(--x)
}

Upvotes: 2

Views: 39

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

The * operator works like this:

  1. Evaluate the left-hand operand; in this case, x yields 3.
  2. Evaluate the right-hand operand. Since --x means "decrement x in place and give me the decremented value" that yields 2.
  3. Multiply the result of Step 1 with the result of Step 2 and take that as the operation result.

It's covered in the spec here, in a section used for lots of the binary operators that can be applied to numbers or strings.

So yes, in a sense you could say that the values are stored in a buffer prior to being multiplied. That buffer is likely to be a CPU register or stack location. In the case of the factorial example you gave, it'll be a stack location (though that's an implementation detail; the JavaScript engine can be implemented in any way provided it produces the specified results).

Upvotes: 3

Related Questions