Skip to content

Instantly share code, notes, and snippets.

@bradjenn
Last active August 29, 2015 14:16
Show Gist options
  • Save bradjenn/67ef1dc11a6e25042331 to your computer and use it in GitHub Desktop.
Save bradjenn/67ef1dc11a6e25042331 to your computer and use it in GitHub Desktop.
Alliants JS Styleguide copy

JS Styleguide

These are my personal preferences to coding javascript, feel free to use this as a template to create your own style guide.

General

  1. Code SHOULD be indented with spaces only (not tabs).
  2. Each level of indentation SHOULD consist of 2 spaces.
  3. Lines SHOULD be 80 characters max (where possible).
  4. Semicolons are NOT optional.

Naming

Overview

Constructor: CamelCase with an initial capital letter

MightyBalrog, MagicWeapon

Public method: camelCase with an initial lowercase letter

castDimensionalDoorway, rollForInitiative

Public variable: camelCase with an initial lowercase letter

materialComponents, hasTrackingAbilities

Private method: camelCase with an initial lowercase letter and underscore

_getHealth

Private variable: camelCase with an initial lowercase letter and underscore

_backstabAbility

Method arguments: camelCase with an initial lowercase letter

halfOrcArmy

Local variables: camelCase with an initial lowercase letter

isHumanoid, levelCount

Object keys: camelCase with an initial lowercase letter

character.armorClass, character.hitPoints

‘Constants’: Uppercase with underscores

CLERIC_PLAYER, GAME_MASTER

Notes

  1. Variable/method names in all lowercase with underscores (AKA 'snake-case') SHOULD NOT be used unless mimicking another API. Object-keys received in snake-case from JSON-parsed API-data may be used as-is, but conversion to camel-case is preferred if possible.
  • Incorrect:

        wizard_hat, vorpal_blade
    
  • Correct:

        wizardHat, vorpalBlade
    
  1. Acronyms in variable/method names SHOULD NOT be upppercased.
  • Incorrect:

        bartenderNPC, newRPG
    
  • Correct:

        bartenderNpc, newRpg
    
  1. Variable/method names SHOULD be written in English.
  • Incorrect:

        dekaiKatana
    
  • Correct:

        giganticSword
    
  1. Variable/method names SHOULD NOT be abbreviated to the point of being unclear.
  • Incorrect:

        wndMnstr[3]
    
  • Correct:

        wanderingMonster[3]
    

Variables

  1. Variables SHOULD be initialized at the top of function scope — if possible, in a way that indicates what type of value they will hold. Null initializations are acceptable. There should be only one var keyword, used on the first variable declaration, and subsequent variables should be declared using an initial comma.
  • Incorrect:

        var magicItemCount;
        var magicSwordName = '';
        var wizardNpc;
    
  • Correct:

        var magicItemCount = 0,
            magicSwordName = '',
            wizardNpc = null;
    
  1. Variable declarations SHOULD NOT include extra spaces before the equals sign to align the variable values.
  • Incorrect:

        var currentThiefLevel = 8,
            canBackstab       = true,
            isNpc             = true;
    
  • Correct:

        var currentThiefLevel = 8,
            canBackstab = true,
            isNpc = true;
    
  1. Anything with meaning should be a constant.
  • Incorrect:

        42
    
  • Correct:

        ANSWER_TO_THE_QUESTION_OF_LIFE
    
  1. self should be used as the variable name to store scope.
  • Incorrect:

        var that = this;
    
  • Correct:

        var self = this;
    

Coding Style

Overview

  1. Function-declarations / function-expressions (in general declarations should be preferred to expressions):

         var checkForSecretDoors = function (race, level) {
           // Stuff for check here
         };
    
    
         function checkForTraps(dexterity, level) {
           // Do stuff to check for traps here
         }
    
  2. Double line before and after blocks of code.

         var checkForSecretDoors = function (race, level) {
           // Stuff for check here
         };
    
    
         function checkForTraps(dexterity, level) {
           // Do stuff to check for traps here
         }
    
  3. No new lines between variable declarations, use new line and a comment to group related variables.

         var foo = bar,
             that = this,
             
             // comment
             ping = pong;
    
  4. If statements:

         if (gotInitiative) {
           attackDragon();
         } else if (speaksDragon) {
           tryNegotiating();
         } else {
           runAway();
         }
    
  5. For statements:

         for (var i = 0; i < guards.length; i++) {
           rollTwentySided(guards[i]);
         }
    
  6. While statements:

         while (charactersInjured) {
           castCureLightWounds();
           charactersInjured = checkCharacterHealth();
         }
    
  7. Switch statements:

         switch (characterClass) {
           case 'ranger':
             // Ranger special stuff here
             // Fallthrough
           case 'fighter':
             // Do fighter stuff
             break;
           case 'magicUser':
             // Do mage-specific stuff
             break;
           default:
             // do nothing
         }
    
  8. Try-catch-finally statements:

         try {
           pickPocket();
         } catch(e) {
           lookInconspicuous();
           reportBack(e);
         } finally {
           runLikeHell();
         }
    
  9. Object literal:

         var obj = {
           spellName: 'Invisible Stalker',
           numberOfFighters: 3,
           checkForTraps: function () {
             // Do trap checking
           }
         };
    
         var obj = {
           staff: 'Staff of the Magi',
           wand: 'Wand of Negation',
           misc: 'Boots of Elvenkind'
         };
    
  10. Array literal:

        var obj = [
          spellName: 'Invisible Stalker',
          numberOfFighters: 3,
          nameOfTrap: 'snare'
        ];
    

Notes

  1. Function literals MUST include a space between the word ‘function’ and the parentheses. (Otherwise it appears to be a function with the name of ‘function.’)
  • Incorrect:

        var rollInitiative = function() { // Roll die here };
    
  • Correct:

        var rollInitiative = function () { // Roll die here };
    
  1. Line continuations should be indicated by double indentation.
  • Incorrect:

        var localMonsterRumors = getLocalGossip(inkeeper,
                                                localInn,
                                                numberOfClerics,
                                                pintsOfAlePurchased,
                                                charismaAjustment);
    
  • Correct:

        var localMonsterRumors = getLocalGossip(inkeeper,
            localInn, numberOfClerics, pintsOfAlePurchased,
            charismaAjustment);
    
  1. If-else statements (also while, et al) should not be written on a single line.
  • Incorrect:

        if (isUndead) grabFire();
    
  • Correct:

        if (isUndead) {
          grabFire(); 
        }
    
  1. Parenthesis in conditional statements (if, while, for, etc.) SHOULD have a space before them.
  • Incorrect:

        if(isNpc) {
          ignoreTalk();
        }
    
  • Correct:

        if (isNpc) {
          ignoreTalk();
        }
    
  1. Parentheses in function-expressions SHOULD NOT have a space before them.
  • Incorrect:

        function getArmorClass (armorType, dexterity) {
          // Get AC stuff here
        }
    
  • Correct:

        function getArmorClass(armorType, dexterity) {
          // Get AC stuff here
        }
    
  1. Commas SHOULD be followed by spaces.
  • Incorrect:

        getExperiencePoints(monster,hitPoints);
    
  • Correct:

        getExperiencePoints(monster, hitPoints);
    
  1. The colon in object literal notation SHOULD have no space in front of it, and be followed by a single space. Entries after the initial item MUST be separated by trailing commas (i.e., ‘comma-first’), not leading commas. The opening bracket MUST NOT be dropped to a new line (so-called ‘Allman style’), due to automatic semicolon-insertion when returning an object literal. Leading commas should align vertically with the closing bracket on the final line.
  • Incorrect:

        var newCharacter = {
          race:'gnome',
          class:'figheter',
          isNpc:false
        };
    
  • Also incorrect:

        var newCharacter = {
          race : 'gnome'
        , class : 'figheter'
        , isNpc : false
        };
    
  • Correct:

        var newCharacter = {
          race: 'gnome',
          class: 'fighter',
          isNpc: false
        };
    
  1. Operators SHOULD both have a space before and after.
  • Incorrect:

        var message = speaksDrow? getMessageinDrow():'You do not speak Drow.';
    
  • Correct:

        var message = speaksDrow ? getMessageinDrow() : 'You do not speak Drow.';
    
  • Incorrect:

        var thaco = hit+adjustment-randomFactor;
    
  • Correct:

        var thaco = hit + adjustment - randomFactor;
    
  1. Lengthy string parameters SHOULD be placed into variables before using.
  • Incorrect:

        var elem = document.getElementById('charClass-' + charClass +
            + '_combatStats-' + armorClass + '-' + toHitBonus);
    
  • Correct:

        var char = 'charClass-' + charClass,
            combat = 'combatStatus-' + armorClass + '-' + toHitBonus,
            elem = document.getElementById(char + '_' + combat);
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment