Why do so many developers write commas this way?
var npm = module.exports = new EventEmitter
, config = require("./lib/config")
, set = require("./lib/utils/set");
Not this way?
var npm = module.exports = new EventEmitter,
config = require("./lib/config"),
set = require("./lib/utils/set");
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
The comma operator in JavaScript is really very simple and, to be 100% honest, you never need to use it.
A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.
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.
They write them with the "," at the beginning of the line to make it easier to maintain the code (add lines or remove/comment out lines).
Given this:
var npm = module.exports = new EventEmitter
, config = require("./lib/config")
, set = require("./lib/utils/set");
It's much cleaner and easier to do this:
var npm = module.exports = new EventEmitter
// , config = require("./lib/config")
, set = require("./lib/utils/set");
as well as add new lines like this:
var npm = module.exports = new EventEmitter
, config = require("./lib/config")
, anothervalue = require("./lib/aval")
, anothervalue2 = require("./lib/aval2")
, set = require("./lib/utils/set");
I never saw that pattern before in JS, so I'm not sure if there are that many developers that use it, but I would guess they do that so variable names are aligned, to emphasize that var
actually defines three variables in your sample code.
If that's the case however, it would be clearer (and less weird) to just use var
three times:
var npm = module.exports = new EventEmitter;
var config = require("./lib/config");
var set = require("./lib/utils/set");
This is strictly a programmer-specific syntaxtual preference. I know a lot of DBA's that sem to prefer that method, while I prefer the trailing comma myself. there's nor real difference except for personal preference/education.
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