I found the following js sample and am confused by the syntax. Notice the statements are separated by commas instead of semicolons. Are commas a valid statement separator in js? I have not seen this before.
$('selector').each(function () { this.onclick = function () { this.select(); }, this.onblur = function () { }, this.onfocus = function () { }, this.onkeyup = function () { } });
A comma operator (,) in JavaScript is used in the same way as it is used in many programming languages like C, C++ etc. This operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand.
In Java, the comma is a separator used to separate elements in a list in various contexts. It is not an operator and does not evaluate to the last element in the list.
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
Commas act as a separator between expressions in a single expression statement. Thus, that (if it had been completed instead of being cut off after the "onkeyup" function) is just a single expression statement.
There's really no reason to code like that, or no really good reason at least. In this particular case it has essentially the same effect as would a series of separate expression statements separated by semicolons.
The comma "operator" is questionable in many cases but useful sometimes:
var index, len; for (index = 0, len = list.length; index < len; ++index) { ... }
for example. It allows one to drop more than one expression (assignments usually) into a grammatical locale that allows just one expression. It's really a sign of syntactic weakness, in my opinion.
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