János
János

Reputation: 35050

Comma operator in JavaScript

Following this tutorial, what do these lines 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 these lines easier be written?

Upvotes: 0

Views: 521

Answers (2)

adeneo
adeneo

Reputation: 318192

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;
},[]);

etc...

Upvotes: 5

samanime
samanime

Reputation: 26547

It's essentially the same as a semi-colon in many cases, so you could rewrite it as this:

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

The difference comes down to lines like declaring variables (like your example), in which the var is applied to each element in the comma-separated list. Beyond that, it's more or less a semi-colon, though it's not recommended to use the comma syntax in most cases.

I personally prefer it for the variables, because I think this look a little cleaner:

var a = 5,
    b = 6,
    c, 
    d;

But others dislike it.

Upvotes: 0

Related Questions