What is the order of evaluation for function arguments in Javascript?

前端 未结 3 939
无人及你
无人及你 2020-12-01 16:05

According to my tests it is always left-to-right

>> console.log( console.log(1), console.log(2) );
1
2
undefined undefined

but I can\

3条回答
  •  长情又很酷
    2020-12-01 16:57

    All the operators in JavaScript evaluate their operands left-to-right, including the function call operator. First the function to call is evaluated then the actual parameters in left-to-right order.

    Section 11.2.3 is the relevant spec section.

    11.2.3 Function Calls

    ...

    2 Let func be GetValue(ref).

    3 Let argList be the result of evaluating Arguments, producing an internal list of argument values (see 11.2.4).

    ...

    and you can see that the ArgumentList production is left-recursive

    11.2.4 Argument lists

    ...

    The production ArgumentList : ArgumentList , AssignmentExpression is evaluated as follows

    and ArgumentList is evaluated before AssignmentExpression in the following verbiage..

    Under EcmaScript 3 some of the comparison operators (<, <=, >, >=) evaluated right to left since a<=b was defined in terms of !(b, but that was widely recognized as a spec error, major interpreters did not implement it that way, and it was fixed in EcmaScript 5.

    From the language spec:

    11.8.5 The Abstract Relational Comparison Algorithm # Ⓣ

    The comparison x < y, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN). In addition to x and y the algorithm takes a Boolean flag named LeftFirst as a parameter. The flag is used to control the order in which operations with potentially visible side-effects are performed upon x and y. It is necessary because ECMAScript specifies left to right evaluation of expressions. The default value of LeftFirst is true and indicates that the x parameter corresponds to an expression that occurs to the left of the y parameter’s corresponding expression. If LeftFirst is false, the reverse is the case and operations must be performed upon y before x. Such a comparison is performed as follows:

提交回复
热议问题