Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are commas necessary in Node.js?

Are there risks incurred when omitting commas in variable declarations for node.js? For example, declaring some global variables like the following works just fine:

express = require('express')
jade = require('jade')

And I don't want to write commas if it's safe not to write them (I don't care about "beauty/clarity of code" arguments).

Important: I mean commas, not semicolons (got 3 answers about semicolons). It's perfectly OK and even recommended to remove semicolons from node.js. The creator of npm also does it: http://blog.izs.me/post/3393190720/how-this-works

If in doubt, check the latest javascript specs: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Note that you also don't need to write

var

for global variables.

But this question is about "commas" so please don't replace commas by semicolons by mistake when editing my question (done before).

like image 801
user1943231 Avatar asked Feb 19 '13 22:02

user1943231


1 Answers

In JavaScript, if you don't write semicolons ; they will be inserted for you, invisibly. And you may not always like where they go.

You are not technically required to end every statement with a semicolon. However, most consider it a good idea.

For more info, peruse through the results of this google search. We've been arguing about this topic for a long time.


Here's an example of why this is more complex than it appears at first glance. While you are not technically required to end every statement with a semicolon, there are a few cases where you MUST, or things break. You cannot completely omit them in most codebases.

foo.def = bar
(function() {
  // some self executing closure
})()

Looks simple enough right? Well the interpreter looks at that and does this:

foo.def = bar(function() {
  // some self executing closure
})()

Which is probably not what you were expecting. The way to fix it, is with a semicolon.

foo.def = bar;
(function() {
  // some self executing closure
})()

There a lot of cases like this. You can either learn them all, and only use them in those cases, and when you inevitably forget you try to debug your code that's doing something so strange and bizarre that you tear your hair out hours... "what do you mean wtfvar is not a function?!? It's not supposed to be a function!"

Or you can just use semicolons with consistency.

like image 109
Alex Wayne Avatar answered Oct 07 '22 13:10

Alex Wayne