24
'use strict';

(true, false, 1);

Do the parentheses create a single expression out of multiple constituent expressions?

I haven't seen this syntax before.

Edit: the original code that piqued interest:

function AddWatermark(controlName, defaultValue, cssValue) {
    document.getElementById(controlName).value == "" 
    && 
    (document.getElementById(controlName).value = defaultValue, document.getElementById(controlName).className = cssValue); //I am interested in this syntax on the RHS of the logical AND operator
}
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

3 Answers3

37

In some programming languages (including c++ and js), the comma operator stands for "Evaluate all the expressions separated by commas and return the last one". For example:

var x = (true, false, 1);
console.log(x) // 1

Here's another one to show you that expressions are evaluated:

var i = 0;
var j = 0;
var x = (i++, j--);
console.log(i, j, x) // 1 -1 0

The function AddWaterMark essentially can be rewritten as:

function AddWatermark(controlName, defaultValue, cssValue) {
    if (document.getElementById(controlName).value == "") { 
        document.getElementById(controlName).value = defaultValue;    
        document.getElementById(controlName).className = cssValue;
    }
}
Nikola Dimitroff
  • 6,127
  • 2
  • 25
  • 31
8

The other answers explained the comma pretty well I guess, and Nikola's answer also shows you how the logical and operator && is used as an alternative of an if statement, due to its short-circuiting evaluation.

As for the brackets - they just alter operator precedence, because the comma operator has a very low precedence naturally.

a && b, c would be interpreted as (a && b), c, i.e. if(a)b;c

a && (b, c) is if(a){b;c}

7

"Do the parenthesis create a single expression out of multiple constituent expressions?"

No, it's the commas that do that. The comma operator evaluates the expressions on both sides of it, and returns the right hand side.

Therefore:

e = (a = b, c = d)

Will perform the two inner assignments, and then assign c to e.

Alnitak
  • 334,560
  • 70
  • 407
  • 495