How to properly read EcmaScript specification

Viewed 622

I'm interested in "HOW it work" knowledge for JavaScript binary logical operations, but I'm stuck at step interpritation.

So that's description of specs

12.13.3

LogicalANDExpression: LogicalANDExpression && BitwiseORExpression

  1. Let lref be the result of evaluating LogicalANDExpression.
  2. Let lval be ? GetValue(lref).
  3. Let lbool be ToBoolean(lval).
  4. If lbool is false, return lval.
  5. Let rref be the result of evaluating BitwiseORExpression.
  6. Return ? GetValue(rref).

And i read this like:

  1. Take memory for left operand and here will be operation result

  2. Get value of left operand in memory and convert it to boolean

  3. if this boolean is false, return left operand

  4. Else take memory for right operand and here will be... BitwiseORExpression <-- what? Bitwise? for what? why?

I'd would like to clarify this algorithm in more human-readable form for understanding how it works. What is p.1 and p.5, what really is lref and rref, what really is LogicalANDExpression and BitwiseORExpression in that context?

2 Answers

BitwiseORExpression here just refers to the (expression for the) right operand, exactly like LogicalANDExpression refers to the left one as you correctly deduced. What it is depends on the code (or rather its parsed form, the AST) that you are currently evaluating, it could be basically anything and does not need to contain an | operator.

This is how i read it (thanks to Bergi for the precisions):

  1. create reference lref to store the result of the evaluation of the left operand expression LogicalANDExpression
  2. create lval that gets the value of lref (evaluates it and throws an error if there is some)
  3. create lbool that gets the boolean value corresponding to lval
  4. if lbool is false, the whole operation will have the value lval and we stop here (that explains why 0 && 'foo' gets 0 as result, and not false)
  5. (if not stopped at precedent step) create reference rref to store the result of the evaluation of the right operand expression BitwiseORExpression
  6. the whole operation will have the value of rref (still throws error if there is some. That explains why 1 && 'foo' gets 'foo' as result, and not 1 or true)
Related