János János - 3 months ago 30
Javascript Question

Comma operator in JavaScript

Following this tutorial, what do these line mean:

var join = require('path').join
, pfx = join(__dirname, '../_certs/pfx.p12');

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

How could lines easier be written?


In this case, the comma separates two variables, and that's it, it's the same as writing

var join = require('path').join;
var pfx  = join(__dirname, '../_certs/pfx.p12');

Instead one can do

var join = require('path').join,
    pfx  = join(__dirname, '../_certs/pfx.p12');

In this case, the comma is just a seperator, much as it would be an object literal or array.

The comma operator, which is only an operator when it acts on two expressions, one on the left side, and one on the right side, can be used when you want to include multiple expressions in a location that requires a single expression.

One example would be in a return statement

[1,2,3].reduce(function(a,b,i) {
    return a[i] = b, a; // returns a;