Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript expressions, comma delimited within parentheses [duplicate]

Tags:

javascript

'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
}
like image 533
Ben Aston Avatar asked Aug 13 '14 07:08

Ben Aston


2 Answers

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;
    }
}
like image 103
Nikola Dimitroff Avatar answered Sep 17 '22 15:09

Nikola Dimitroff


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}

like image 42
user3936908 Avatar answered Sep 17 '22 15:09

user3936908