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. If LHE is true, evaluate RHE
LHE || RHE
1. Always evaluate LHE
2. If LHE is false, evaluate RHE
LHE, RHE
1. Always evaluate LHE
2. Always evaluate RHE
However, I have made a jsfiddle test enter link description here with the code below, and it appears that the LHE must be surrounded by parentheses if the operator is &&
.
// Works fine
(function one(window) {
window.testOne = function testOne() {
alert("Test one");
}, testOne();
})(window);
// Works, but JSHint complains at *:
// "Expected an assignment or function call but saw instead an expression"
(function two(window) {
(window.testTwo = function testTwo() {
alert("Test two");
}) && testTwo(); // *
})(window);
// Looks good to JSHint, but fails at runtime:
// "ReferenceError: Can't find variable: testThree"
(function three(window) {
window.testThree = function testThree() {
alert("Test three");
} && testThree();
})(window);
Can you explain why testOne
(using ,
) does not require parentheses around the first expression, but testTwo
(using &&
) does? And why does JSHint consider test()
not to be a function call?