Which of the following expressions will always precede left to right in all browsers(particularly IE6+, F3+, Opera 9+, Chrome)? For example the window should always alert
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:
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)));
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.