Skip to content Skip to sidebar Skip to footer

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();
  1. Assign window.testTwo = function testTwo() { alert("Test two") };
  2. Call testTwo()

But this other one attempts to call before the assignment

window.testThree = functiontestThree() {
    alert("Test three");
} && testThree();
  1. Evaluate the function expression (not declaration, so no testThree variable is created!) function testThree() { alert("Test three") }
  2. Call and assign window.testThree = testThree();

However, testThree is undeclared. So an error is thrown.

Post a Comment for "Understanding The Javascript Comma Operator"