Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS statement separator with commas

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 () {             }     }); 
like image 596
John Livermore Avatar asked Dec 14 '11 14:12

John Livermore


People also ask

How do you use commas in JavaScript?

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.

What is the use of comma operator in Java?

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.

What is comma operator in C?

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.


1 Answers

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.

like image 150
Pointy Avatar answered Oct 03 '22 01:10

Pointy