Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm willing to, please don't withhold enlightenment to spite one guy.


I write Javascript for a living, and the code standard requires semicolons.

Anyway variables in javascript have function scope, so two variables with the same name in the same function always refer to the same value, even if declared twice.

As a result I like to write all the variable statements at the top of each function, all in one var statement.

The problem then becomes that you write var a, b, c, d; and then later want to add variable e. If you aren't careful you might accidentally write var a, b, c, d; e; if you do that, the program may still work but e now has global scope. This results in nearly impossible to find bugs that may only happen if the function is recursive or it is called (perhaps indirectly) by some other function with a similarily named variable.

Considering that semicolons insertion mostly works, and the other can be a huge pain in the rear end, I can understand why people would want to skip the semicolons.


If you aren't careful, you might accidentally write var a, b, c, d, r;


I think it's generally a good idea to avoid declaring multiple variables in the same line (unless you have a very good reason). The space you "save" isn't worth the maintainability penalty. This is a habit I have from C where

  int* a, b
declares "a" as ( int* ) and b as ( int ). Instead, I just write

  int *a;
  int *b;


If you get in the habit of writing the * next to the variable then you can't make the mistake. int *a, b, c[]; perfectly clear.


The JS interpreter shares your preference of writing all var declarations at the top - in fact, at interpretation time they will be "hoisted" to the top of the scope. In other words:

  foo()
  var bar = 1;
is actually run as

  var bar;
  foo();
  bar = 1;


True, and that was part of what I was trying to articulate.


But this is a simple error caught by js(h/l)int. And it's especially easy to spot if you just declare each var one after another:

    var a,
        b,
        c,
        d;
        e;
         
Then your editor (which you've a integrated a linter... right?) will protested:

    yourJsFile.js |5 warning| 'e' was used before it was defined.
And if you have a global by the same name you'll see:

    yourJsFile.js |5 warning| Expected an assignment or function call and instead saw an expression.
Granted, if you assign it a default value then, yes you're going to have a bad time. But if you follow the white spacing rules of jsLint it will catch the obvious error.


Strict mode should save you from a lot of those.

    (function () {
      'use strict';
      var a = 1; b = 2;
    }());
    // ReferenceError: b is not defined




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: