Javascript evaluation order for operators

情到浓时终转凉″ 提交于 2019-11-29 04:23:46

ECMAScript 5 specifies the order of evaluation of the operands for all operators. In the case of every operator in your code snip the evaluation order is left-to-right. I'm not sure anyone could answer about the behavior of all browsers though.

Edit: See also ECMAScript 3. Evaluation order is defined the same way.

Evaluating the expression into a value (e.g. involving a function call) is always done left to right.

However, once you are comparing two values, they are not converted into primitives in order to do the actual comparison in a left to right fashion. Try the following in Chrome, for example:

var l = {valueOf: function() { alert("L"); }};
var r = {valueOf: function() { alert("R"); }};

l < r; //alerts "L", then "R"
l > r; //alerts "R", then "L"

Operator precedence and order of evaluation are two entirely different things. In the expression "sqrt(9) + sqrt(16) * sqrt(25)" it is misleading to say that "the multiplication is done first.". It is correct to say "multiplication takes precedence over addition.".

The operations are:

  1. sqrt(9)
  2. sqrt(16)
  3. sqrt(25)
  4. 4 * 5
  5. 3 + 20

The first three could be done in any order, or -- gasp -- simultaneously if you have a four-core CPU and a browser that can take advantage of it. 1 must be done before 5, 2 and 3 must be done before 4, and 4 must be done before 5. There are no other guarantees.

In the expression "a && (b / a)", JavaScript guarantees that a is evaluated first and b / a is not evaluated if a is zero. Many other languages including Fortran do not guarantee this, and can get a division-by-zero exception.

I'm not sure what your use-case is, but this might be an option:

function add() {
  var retval = 0;
  for (var i = 0; i < arguments.length; i++) {
    retval += arguments[i];
  }
  return retval;
}

function echoNum(num) {
  alert("Num: " + num);
  return num;
}

alert("Result: " + add(echoNum(1), echoNum(2)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!