0

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?

3

2 Answers 2

5

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...

Sign up to request clarification or add additional context in comments.

2 Comments

yep it's shorthand so you don't have to write var twice when declaring variables in succession
Shorthand, yes; but this notation doesn't make for clean git diffs when adding or deleting variables at the beginning or end. For that reason, I dislike it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.