'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
}
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;
}
}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With