Skip to content

Instantly share code, notes, and snippets.

@lxe
Last active December 15, 2015 11:49
Show Gist options
  • Save lxe/5255588 to your computer and use it in GitHub Desktop.
Save lxe/5255588 to your computer and use it in GitHub Desktop.

lxe's javascript style guide.

Can be applied to C as well.

Focus on the first 3 headings.

1. Consistency

Keep things consistent. Don't vary your indent, spacing, braces, etc... across lines, files and project.

2. Readability

Make sure your code is easy on the eyes. If you're supposedly showing someone what your code does, line by line, make sure they aren't struggling to follow it.

3. Indent

2 spaces.

Wrong

function foo() {
    var a = j;
    doThing(function() {
        thingy();
    });
}

Very Wrong

function foo() {
   var a = j;
            doThing(function() {
          thingy();
            });
   }

Right

function foo() {
  var a = j;
  doThing(function() {
    thingy();
  });
}

4. Spacing

Give operators, keywords and braces room to breathe.

Wrong

//a cramped comment
var a=5;
var b=c+d;
var g='Hello'+'world';
var e={foo:'bar',zoo:'zar'};

var f=function(arg1,arg2);
function f(arg1,arg2) {}

for(i=0;i<=4;i++) {}
for( i=0; i<=4; i++ ) {}
for( i=0 ; i<=4 ; i++ ) {}

Very Wrong

//a cramped comment
var a=5;
var b = c+d;
var g= 'Hello' +  'world';
var e={foo:'bar'  ,zoo : 'zar' };

var f= function(arg1, arg2) ;
function f ( arg1,arg2) {}

for( i=0;i<=4;i++) {}
for( i=0; i<=4; i++ ) {}
for( i=0 ; i<=4 ; i++ ) {}

Right

// the space in front of this comment is easy on the eyes
var a = 5;
var b = c + d;
var g = 'Hello' + 'World';
var e = { foo: 'bar', zoo: 'zar' };

var f = function (arg1, arg2);
// OR
var f = function(arg1, arg2);

function f(arg1, arg2) {}
// OR
function f (arg1, arg2) {}

for (i = 0; i <= 4; i++) {}
// '++' and '--' operators are OK to place flush to the variable

5. Strings

Use single quotes.

Wrong

var s = "an \"ugly\" string";

Very Wrong

var s = "a string in doublequotes"
  , k = 'a string in singlequotes'

Right

var s = 'a "pretty" string';

6. Variable Declarations.

  • Keep declarations grouped semantically.
  • Avoid too many vars
  • Use commas in front of line for simple declarations.

Ugly

// var soup
var a = 5;
var b = 6;
var c = { foo: 'bar' };

// comma hell
var a = 5
  , b = (function () {
    return {
      foo : 'bar'
    }
  })()
  , c = 6;
  
// semantic mess
var mom = person()
  , dad = person()
  , somethingTotallyUnrelated = foobar(1, 2, 3)
  , son = person()
  , daughter = person();

Pretty

var a = 5
  , b = 6
  , c = { foo: 'bar' };

var a = 5
  , c = 6;
  
var b = (function () {
  return {
    foo : 'bar'
  }
})();

var mom = person()
  , dad = person()
  , son = person()
  , daughter = person();
  
var somethingTotallyUnrelated = foobar(1, 2, 3);

7. Object Variables

Commas at the end of line to preserve indent.

Wrong

var a = {
  foo : 'bar'
  , bar : 'foo'
  , zoo : {
    goo : 'gar'
    , too : 'tar'
  }
};

Right

var a = {
  foo : 'bar',
  bar : 'foo',
  zoo : {
    goo : 'gar',
    too : 'tar'
  }
};

8. Conditionals

No new lines before else and else if

Wrong

if (foo === bar) {
  doThing();
}
else if (thing === widget) {
  doAnotherThing();
}
else {
  blah();
}

Right

if (foo === bar) {
  doThing();
} else if (thing === widget) {
  doAnotherThing();
} else {
  blah();
}

9. Switch

Give the code some room to breathe.

Wrong

switch (foo) {
  case 'bar': doThing(); doAnotherThing(); frobWidgets(widget1, widget2); break;
  case 'widget': doADifferentThing(); doAnotherDifferentThing(); frobExtraWidgets(widget3, widget4); break;
  default: frobDefaultWidgets(); break;
}

Right

switch (foo) {
  case 'bar':
    doThing();
    doAnotherThing();
    frobWidgets(widget1, widget2);
    break;
  case 'widget':
    doADifferentThing();
    doAnotherDifferentThing();
    frobExtraWidgets(widget3, widget4);
    break;
  default:
    frobDefaultWidgets();
    break;
}

10. Semicolons 1

Use them. Unless you know when you have to use them.

Wrong

var g = 6
var a = 7

(function() {
  return {
    foo : 'bar'
  }
})()

frob(1, 2, 3)

Right

var g = 6;
var a = 7;

(function() {
  return {
    foo : 'bar'
  };
})();

frob(1, 2, 3);

10.1 More Semicolons

Wrong

var g = function () {
  return true
}

function f () {
  return true
};

for (var i = 0; i < 10; i++) {
  f();
};

Right

var g = function () {
  return true;
};

function f () {
  return true;
}

for (var i = 0; i < 10; i++) {
  f();
}

11. Line Breaks

Keep your lines under 100 - 130 characters.

Wrong

if ((thingExists(thing1) || thingExists(thing2)) && (thingExists(thing2) && thingExists(thing3)) || (thingExists(thing4) && thingExists(thing5))) {
  doStuff();
}

var g = isDone(something + anotherThing) ? someValue + someFunction(arg1, arg2) : anotherValue + anotherFunction(arg3, arg4));

Right

if ((thingExists(thing1) || thingExists(thing2)) 
  && (thingExists(thing2) && thingExists(thing3)) 
  || (thingExists(thing4) && thingExists(thing5))) {

  doStuff();
}

var g = isDone(something + anotherThing) 
  ? someValue + someFunction(arg1, arg2) 
  : anotherValue + anotherFunction(arg3, arg4));
@jmonster
Copy link

double emphasize the word spaces and not tabs set to 2 spaces

@jmonster
Copy link

semicolons on closing brackets is 100% redundant as the bracket unambiguously closes the statement?

@lxe
Copy link
Author

lxe commented Apr 24, 2013

@jmonster

semicolons on closing brackets is 100% redundant as the bracket unambiguously closes the statement?

only after an expression or returns. Blocks of 'for', 'while', 'function' need no semicolons.

@mattlgy
Copy link

mattlgy commented Jun 12, 2013

I think the only time parens should be next to something is when its calling a function, and then it is mandatory.

Wrong:

if(a || b) {...}
var foo = function(a, b) {..};
function foo(a, b) {..}
var result = foo (a, b);

Right:

if (a || b)
var foo = function (a, b) {..};
function foo (a, b) {..}
var result = foo(a, b);

It makes it very clear what is a function call and not. Which, I think, is a good thing for a language that plays fast and lose with anonymous function.

@benmkramer
Copy link

Notice an error with one of the "correct" blocks of javascript.

https://gist.github.com/lxe/5255588#pretty

var a = 5;
  , b = 6;
  , c = { foo: 'bar' };

The variable declarations for a and b should not have semicolons at the end, as far as I am concerned.

@lxe
Copy link
Author

lxe commented Oct 3, 2013

@benkramerbb thank you. Fixed.

@Cauldrath
Copy link

Do we want to include something about whether to drop braces or not?

Wrong:

if (blah)
{
  doSomething();
}

Right:

if (blah) {
  doSomething();
}

Also, if this applies to C, as well, then I'd like to formally object to putting a space between ifs and the parenthesis. It burns my eyes, but I can kind of see the reason to do it with Javascript. But whitespace that isn't used for alignment has always been a peeve of mine.

@ksandrock
Copy link

Can someone help me understand the 2 spaces versus tabs convention? From what I can tell tabs are the clear choice, but I have an open mind and would certainly welcome any knowledge anyone is able to drop on me.

It seems to me that more pronounced indentations would only serve to make the code more clear and readable. I also think using tabs makes it a lot less likely that someone would accidentally misalign segments they intended to be aligned. I have personally had issues with adjusting the indentation of large code segments when pasting them into my code because the tabbing out/in multiple lines functionality does work properly (even when I adjust my IDE settings accordingly).

Since tabs are meant specifically for indentation it seems they would be more correct on a semantic level, but also using spaces for everything versus using a distinct character for indentation limits how that code can be adjusted or displayed differently when shared among varying IDEs. In other words, the inability to differentiate between indenting spaces vs others is limiting.

I asked around a while ago and the only reason I have ever heard for using spaces is that some IDE's and operating systems do not interpret a tab as four spaces, but in these seemingly rare cases that can be very easily remedied with a single configuration change so I'm not sure I'd consider this a valid issue.

@lxe
Copy link
Author

lxe commented Jan 2, 2014

@ksandrock 2 spaces is a convention for the JS community:

https://github.com/styleguide/javascript
https://github.com/airbnb/javascript
http://dailyjs.com/2012/01/12/style/
etc...

The cons and pros apply here, but consistency takes precedence.

Just like 8 spaces for linux kernel devs, and tabs for java.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment