Understanding The Javascript Comma Operator
This article by Angus Croll explains the JavaScript comma operator like this: //(LHE: left hand expression, RHE right hand expression) LHE && RHE 1. Always evaluate LHE 2.
Solution 1:
It's a case of operator precedence. The operators you use have the following precedence: &&, ||, =, ,.
This means var ... = ... && ... is equivalent to var ... = (... && ...) but var ... = ... , .... is equivalent to (var ... = ...) , .....
You can check the precedence here, for example.
Solution 2:
This code first assigns and then calls
(window.testTwo = functiontestTwo() {
alert("Test two");
}) && testTwo();
- Assign
window.testTwo = function testTwo() { alert("Test two") }; - Call
testTwo()
But this other one attempts to call before the assignment
window.testThree = functiontestThree() {
alert("Test three");
} && testThree();
- Evaluate the function expression (not declaration, so no
testThreevariable is created!)function testThree() { alert("Test three") } - Call and assign
window.testThree = testThree();
However, testThree is undeclared. So an error is thrown.
Post a Comment for "Understanding The Javascript Comma Operator"