Skip to content
This repository was archived by the owner on Oct 22, 2024. It is now read-only.

Latest commit

History

210 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

uShip JavaScript Style Guide () {

A mostly reasonable approach to JavaScript, based on AirBnb's style guide

  1. Types
  2. Objects
  3. Arrays
  4. Strings
  5. Functions
  6. Properties
  7. Variables
  8. Hoisting
  9. Conditional Expressions & Equality
  10. Blocks
  11. Comments
  12. Whitespace
  13. Commas
  14. Semicolons
  15. Type Casting & Coercion
  16. Naming Conventions
  17. Accessors
  18. Constructors
  19. Events
  20. Modules
  21. jQuery
  22. ES5 Compatibility
  23. Testing
  24. Performance
  25. Resources
  26. In the Wild
  27. Translation
  28. The JavaScript Style Guide Guide
  29. Contributors
  30. License
  • Primitives: When you access a primitive type you work directly on its value

    • string
    • number
    • boolean
    • null
    • undefined
    letfoo=1,bar=foo;bar=9;console.log(foo,bar);// => 1, 9
  • Complex: When you access a complex type you work on a reference to its value

    • object
    • array
    • function
    letfoo=[1,2],bar=foo;bar[0]=9;console.log(foo[0],bar[0]);// => 9, 9

    ↑ Back to top

  • Use the literal syntax for object creation.

    // badletitem=newObject();// goodletitem={};
  • (ES6) Use enhanced object literal instantiation to reduce boilerplate when assigning values to properties, methods, and dynamically computed property names:

    // bad
    let private = true,
    weakness = 'kryptonite';
    let superman = {
    private: private,
    fly: function () {
    console.log('Faster than a speeding bullet');
    }
    }
    superman[weakness] = true;
    // good
    let private = true,
    weakness = 'kryptonite';
    let superman = {
    private,
    fly () {
    console.log('Faster than a speeding bullet');
    },
    [weakness]: true
    }
    
  • Don't use reserved words as keys. It won't work in IE8. More info

    // badletsuperman={default: {clark: 'kent'},private: true};// goodletsuperman={defaults: {clark: 'kent'},hidden: true};
  • Use readable synonyms in place of reserved words.

    // badletsuperman={class: 'alien'};// badletsuperman={klass: 'alien'};// goodletsuperman={type: 'alien'};

    ↑ Back to top

  • Use the literal syntax for array creation

    // badletitems=newArray();// goodletitems=[];
  • If you don't know array length use Array#push.

    letsomeStack=[];// badsomeStack[someStack.length]='abracadabra';// goodsomeStack.push('abracadabra');
  • (ES6) To copy an array, use the spread operator:

    letitems=[1,2,3],itemsCopy;// badfor(leti=0;i<items.length;i++){itemsCopy[i]=items[i];}// gooditemsCopy=[...items];
  • (ES5) In ES5 environments, use Array#slice to copy an array.

    varitems=[1,2,3],itemsCopy;// badfor(vari=0;i<items.length;i++){itemsCopy[i]=items[i];}// gooditemsCopy=items.slice();
  • (ES6) To convert an array-like object to an array, use the spread operator.

    letnodeList=document.getElementsByTagName('a'),nodesArray=[...nodesList];
  • (ES5) To convert an array-like object to an array in ES5 environments, use Array#slice.

    functiontrigger(){varargs=Array.prototype.slice.call(arguments);
    ...
    }
  • (ES5) To convert an array-like object to an array in ES5 environments, use Array#slice.

    functiontrigger(){varargs=Array.prototype.slice.call(arguments);
    ...
    }

    ↑ Back to top

  • Use single quotes '' for strings

    // badconstNAME="Bob Parr";// goodconstNAME='Bob Parr';
  • (ES6) Use template strings for interpolating variables in strings

    // badletfullName='Bob '+this.lastName;// goodletfullname=`Bob ${this.lastName}`;
  • (ES6) Strings longer than 80 characters should be written across multiple lines using template strings:

    // badleterrorMessage='This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';// badleterrorMessage='This is a super long error that \was thrown because of Batman. \When you stop to think about \how Batman had anything to do \with this, you would get nowhere \fast.';// goodleterrorMessage=`This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.`;
  • (ES5) Strings longer than 80 characters should be written across multiple lines using string concatenation in ES5 environments.

  • Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion

    // badvarerrorMessage='This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';// badvarerrorMessage='This is a super long error that \was thrown because of Batman. \When you stop to think about \how Batman had anything to do \with this, you would get nowhere \fast.';// goodvarerrorMessage='This is a super long error that '+'was thrown because of Batman. '+'When you stop to think about '+'how Batman had anything to do '+'with this, you would get nowhere '+'fast.';
  • When programatically building up a string, use Array#join instead of string concatenation. Mostly for IE: jsPerf.

    letitems,messages,length;messages=[{state: 'success',message: 'This one worked.'},{state: 'success',message: 'This one worked as well.'},{state: 'error',message: 'This one did not work.'}];length=messages.length;// badfunctioninbox(messages){items='<ul>';for(leti=0;i<length;i++){items+='<li>'+messages[i].message+'</li>';}returnitems+'</ul>';}// goodfunctioninbox(messages){items=[];for(leti=0;i<length;i++){items[i]=messages[i].message;}return'<ul><li>'+items.join('</li><li>')+'</li></ul>';}

    ↑ Back to top

  • There are lots of ways to declare and use functions. Here's a list:

    // anonymous function expressionletanonymous=function(){returntrue;};// named function expressionletnamed=functionnamed(){returntrue;};// arrow function expressionletdogFilter=animal=>typeofanimal==='Dog';// immediately-invoked function expression (IIFE)(function(){console.log('Welcome to the Internet. Please follow me.');})();// function declarationfunctiongreetings(yourName){console.log(`Glad you could join us, ${yourName}`);}
  • Um, that's a lot. Which to use? Here are some rules of thumb:

  • (ES6) For simple callbacks and functions passed as parameters, use arrow function shorthand. Arrow functions are lexically scoped, which makes them great for things like event handlers:

    // badletself=this;$('#hit-me').on('click',function(){self.hitCount++;});// good$('#hit-me').on('click',e=>this.hitCount++);
  • For multiline functions, use function declarations. Function declarations are hoisted, so you can use the functions anywhere in the scope where they are declared.

    // badletmapMyLocation=function(){//do a lot of stuff}// goodfunctionmapMyLocation(){// do a lot of stuff}
  • Don't abuse function parameters by deeply nesting anonymous functions. Instead, declare the function in the top-level scope and pass it by name.

    // badletcontents;fs.readFile('first.txt',function(err,data){if(err){fs.readFile('url.txt',function(err,data){if(!err){http.get(data).then(function(resp){contents=resp.body;});}});}else{contents=data;}});// goodletcontents;fs.readFile('first.txt',handleFileRead);functionhandleFileRead(err,data){if(err){fs.readFile('url.txt',handleFallbackRead);}else{contents=data;}}functionhandleFallbackRead(err,data){if(err)return;http.get(data).then(resp=>contents=resp.body);}
  • Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.

  • Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.

    // badif(currentUser){functiontest(){console.log('Nope.');}}// goodlettest;if(currentUser){test=functiontest(){console.log('Yup.');};}
  • (ES6) Prefer the use of rest params instead of the arguments keyword.

    // bad
    function stuff () {
    console.log(arguments.length);
    }
    // good
    function betterStuff (...args) {
    console.log(args.length);
    }
    
  • Never name a parameter arguments, this will take precedence over the arguments object that is given to every function scope.

    // badfunctionnope(name,options,arguments){// ...stuff...}// goodfunctionyup(name,options,args){// ...stuff...}

    ↑ Back to top

  • Use dot notation when accessing properties.

    letluke={jedi: true,age: 28};// badletisJedi=luke['jedi'];// goodletisJedi=luke.jedi;
  • Use subscript notation [] when accessing properties with a variable.

    letluke={jedi: true,age: 28};functiongetProp(prop){returnluke[prop];}letisJedi=getProp('jedi');

    ↑ Back to top

  • Always use var, let or const to declare variables. Not doing so will result in strict mode errors.

    // badsuperPower=newSuperPower();// goodletsuperPower=newSuperPower();
  • (ES6) Use only let or const instead of var. If you have a specific need for a function-scoped variable instead of a block-scoped one, write a comment explaining why.

    // badvarhowManyTimes=5;for(vari=0;i<howManyTimes;i++){
    ...
    }// goodconstHOW_MANY_TIMES=5;for(leti=0;i<howManyTimes,i++){
    ...
    }
  • Use one let or var declaration for multiple variables and declare each variable on a newline.

    // badletitems=getItems();letgoSportsTeam=true;letdragonball='z';// goodletitems=getItems(),goSportsTeam=true,dragonball='z';
  • (ES6) Use one const declaration per line, to emphasize the immutability of the assignment.

    // badconstSHAPE='circle',WEIGHT=25;// goodconstSHAPE='circle';constWEIGHT=25;
  • Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables. One variable per line. Move multiline declarations -- like object literals -- to their own let or var expression.

    // badleti,len,dragonball,items=getItems(),goSportsTeam=true;// badleti,items=getItems(),dragonball,goSportsTeam=true,len;// badletitems=getItems(),startingInventory={potions: 10,weapons: 5,staffs: 1},dragonball;// goodletitems=getItems(),goSportsTeam=true,dragonball,length,i;// goodletitems=getItems(),dragonball;letstartingInventory={potions: 10,weapons: 5,staffs: 1};
  • Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.

    // badfunction(){test();console.log('doing stuff..');//..other stuff..letname=getName();if(name==='test'){returnfalse;}returnname;}// goodfunction(){letname=getName();test();console.log('doing stuff..');//..other stuff..if(name==='test'){returnfalse;}returnname;}// badfunction(){letname=getName();if(!arguments.length){returnfalse;}returntrue;}// goodfunction(){if(!arguments.length){returnfalse;}letname=getName();returntrue;}

    ↑ Back to top

  • Variable declarations get hoisted to the top of their scope, their assignment does not.

    // we know this wouldn't work (assuming there// is no notDefined global variable)functionexample(){console.log(notDefined);// => throws a ReferenceError}// creating a variable declaration after you// reference the variable will work due to// variable hoisting. Note: the assignment// value of `true` is not hoisted.functionexample(){console.log(declaredButNotAssigned);// => undefinedletdeclaredButNotAssigned=true;}// The interpreter is hoisting the variable// declaration to the top of the scope.// Which means our example could be rewritten as:functionexample(){letdeclaredButNotAssigned;console.log(declaredButNotAssigned);// => undefineddeclaredButNotAssigned=true;}
  • Anonymous function expressions hoist their variable name, but not the function assignment.

    functionexample(){console.log(anonymous);// => undefinedanonymous();// => TypeError anonymous is not a functionletanonymous=function(){console.log('anonymous function expression');};}
  • Named function expressions hoist the variable name, not the function name or the function body.

    functionexample(){console.log(named);// => undefinednamed();// => TypeError named is not a functionsuperPower();// => ReferenceError superPower is not definedletnamed=functionsuperPower(){console.log('Flying');};}// the same is true when the function name// is the same as the variable name.functionexample(){console.log(named);// => undefinednamed();// => TypeError named is not a functionletnamed=functionnamed(){console.log('named');}}
  • Function declarations hoist their name and the function body.

    functionexample(){superPower();// => FlyingfunctionsuperPower(){console.log('Flying');}}
  • For more information refer to JavaScript Scoping & Hoisting by Ben Cherry

    ↑ Back to top

  • Use === and !== over == and !=.

  • Conditional expressions are evaluated using coercion with the ToBoolean method and always follow these simple rules:

    • Objects evaluate to true
    • Undefined evaluates to false
    • Null evaluates to false
    • Booleans evaluate to the value of the boolean
    • Numbers evaluate to false if +0, -0, or NaN, otherwise true
    • Strings evaluate to false if an empty string '', otherwise true
    if([0]){// true// An array is an object, objects evaluate to true}
  • Use shortcuts.

    // badif(name!==''){// ...stuff...}// goodif(name){// ...stuff...}// badif(collection.length>0){// ...stuff...}// goodif(collection.length){// ...stuff...}
  • For more information see Truth Equality and JavaScript by Angus Croll

    ↑ Back to top

  • Use braces with all multi-line blocks.

    // badif(test)returnfalse;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

    ↑ Back to top

  • Use /** ... */ for multiline comments. Include a description, specify types and values for all parameters and return values.

    // bad// make() returns a new element// based on the passed in tag name//// @param <String> tag// @return <Element> elementfunctionmake(tag){// ...stuff...returnelement;}// good/** * make() returns a new element * based on the passed in tag name * * @param <String> tag * @return <Element> element */functionmake(tag){// ...stuff...returnelement;}
  • Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.

    // badconstACTIVE=true;// is current tab// good// is current tabconstACTIVE=true;// badfunctiongetType(){console.log('fetching type...');// set the default type to 'no type'lettype=this._type||'no type';returntype;}// goodfunctiongetType(){console.log('fetching type...');// set the default type to 'no type'lettype=this._type||'no type';returntype;}
  • Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME -- need to figure this out or TODO -- need to implement.

  • Use // FIXME: to annotate problems

    functionCalculator(){// FIXME: shouldn't use a global heretotal=0;returnthis;}
  • Use // TODO: to annotate solutions to problems

    functionCalculator(){// TODO: total should be configurable by an options paramthis.total=0;returnthis;}

    ↑ Back to top

  • In general, keep lines short. Use newlines between blocks or chunks of related code.

    // badthis.weightUnits=ko.computed(()=>(this.systemOfMeasurement()==='Metric') ? uship.localization['MainKg'] : uship.localization['MainLbs']);functionanotherFunction(){letfoo=1;}// goodthis.weightUnits=ko.computed(()=>(this.systemOfMeasurement()==='Metric') ?
    uship.localization['MainKg'] :
    uship.localization['MainLbs']);functionanotherFunction(){letfoo=1;}
  • Use soft tabs set to 4 spaces. Don't mix hard tabs and spaces.

    // badfunction(){____varname;}// badfunction(){∙∙varname;}// badfunction(){∙varname;}// goodfunction(){∙∙∙∙varname;}
  • Place 1 space before the leading brace. For function declarations, place 1 space between the function keyword and the arguments list.

    // badfunctiontest(){console.log('test');}// badfunctiontest(){console.log('test');}// goodfunctiontest(){console.log('test');}// baddog.set('attr',{age: '1 year',breed: 'Bernese Mountain Dog'});// gooddog.set('attr',{age: '1 year',breed: 'Bernese Mountain Dog'});
  • Set off operators with spaces.

    // badletx=y+5;// goodletx=y+5;
  • Use a newline between key/value pairs in an object literal. Place 1 space between keys and values. You can choose to tab-align values as long as the result is more readable.

    // badvardog={breed: 'Maltese',color: 'white',age: '3 years'};// badletdog={breed:'Maltese',color:'white',age:'3 years'};// goodletdog={breed: 'Maltese',color: 'white',age: '3 years'};// badletdog={breed: 'Maltese',color: 'white',age: '3 years',aReallyLongPropertyNameMakesAlignmentHardToRead: true};// acceptableletdog={breed: 'Maltese',color: 'white',age: '3 years',adorable: 'obviously'};
  • Use indentation when making long method chains.

    // bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// good$('#items').find('.selected').highlight().end().find('.open').updateCount();// badvarleds=stage.selectAll('.led').data(data).enter().append('svg:svg').class('led',true).attr('width',(radius+margin)*2).append('svg:g').attr('transform','translate('+(radius+margin)+','+(radius+margin)+')').call(tron.led);// goodvarleds=stage.selectAll('.led').data(data).enter().append('svg:svg').class('led',true).attr('width',(radius+margin)*2).append('svg:g').attr('transform','translate('+(radius+margin)+','+(radius+margin)+')').call(tron.led);

    ↑ Back to top

  • Leading commas: Nope.

    // badletonce,upon,aTime;// goodletonce,upon,aTime;// badlethero={firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};// goodlethero={firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};
  • Additional trailing comma: Nope. This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 (source):

Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.

```javascript
// bad
let hero = {
firstName: 'Kevin',
lastName: 'Flynn',
};
// bad
let heroes = [
'Batman',
'Superman',
];
// good
let hero = {
firstName: 'Kevin',
lastName: 'Flynn'
};
// good
let heroes = [
'Batman',
'Superman'
];
```
**[&#8593; Back to top](#TOC)**
  • Yup. Javascript will automatically insert semicolons -- that it's they're optional in the strict sense. But leaving out semicolons can cause some pernicious bugs, particularly when multiple people are working on the same code, or when not everyone is an expert on the edge case rules for semicolon insertion. So for consistency's sake, always use them.

    // bad(function(){letname='Skywalker'returnname})()// good(function(){letname='Skywalker';returnname;})();// good;(function(){letname='Skywalker';returnname;})();

    ↑ Back to top

  • Perform type coercion at the beginning of the statement.

  • Strings:

    // => this.reviewScore = 9;// badlettotalScore=this.reviewScore+'';// goodlettotalScore=''+this.reviewScore;// badlettotalScore=''+this.reviewScore+' total score';// goodlettotalScore=this.reviewScore+' total score';
  • Use parseInt for Numbers and always with a radix for type casting.

    letinputValue='4';// badletval=newNumber(inputValue);// badletval=+inputValue;// badletval=inputValue>>0;// badletval=parseInt(inputValue);// goodletval=parseInt(inputValue,10);
  • If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.

  • Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but Bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion

    // good/** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. */letval=inputValue>>0;
  • Booleans:

    letage=0;// badlethasAge=newBoolean(age);// goodlethasAge=Boolean(age);// goodlethasAge=!!age;

    ↑ Back to top

  • Avoid single letter names. Be descriptive with your naming.

    // badfunctionq(){// ...stuff...}// goodfunctionquery(){// ..stuff..}
  • Use camelCase when naming objects, functions, and instances

    // badletOBJEcttsssss={};letthis_is_my_object={};functionc(){};letu=newuser({name: 'Bob Parr'});// goodletthisIsMyObject={};functionthisIsMyFunction(){};letuser=newUser({name: 'Bob Parr'});
  • Use PascalCase when naming constructors or classes

    // badfunctionuser(options){this.name=options.name;}varbad=newuser({name: 'nope'});// goodclassUser{constructor(options){this.name=options.name;}}functionUser(options){this.name=options.name;}vargood=newUser({name: 'yup'});
  • Use a leading underscore _ when naming private properties

    // badthis.__firstName__='Panda';this.firstName_='Panda';// goodthis._firstName='Panda';
  • When saving a reference to this use self. Prefer arrow function expressions or bind to replace the need for saving a reference to this. Stick to a single paradigm -- don't mix this and self in the same context.

    // badfunction(){letthat=this;returnfunction(){console.log(that);};}function(){letself=this;this.trait='Inconsistency';returnfunction(){console.log(self);};}// goodfunction(){letself=this;returnfunction(){console.log(self);};}// betterfunction(){returnfunction(){console.log(this);}.bind(this);}// bestfunction(){return()=>console.log(this);}
  • Name your functions. This is helpful for stack traces. (You don't have to worry about this if you use function declarations as recommended.)

    // badletlog=function(msg){console.log(msg);};// goodletlog=functionlog(msg){console.log(msg);};

    ↑ Back to top

  • Accessor functions for properties are not required

  • If you do make accessor functions use getVal() and setVal('hello')

    // baddragon.age();// gooddragon.getAge();// baddragon.age(25);// gooddragon.setAge(25);
  • If the property is a boolean, make the property name a "statement of fact" using a prefix like "is", "has", or "should"

    // badif(!dragon.age()){returnfalse;}// goodif(!dragon.hasAge()){returnfalse;}
  • It's okay to create get() and set() functions, but be consistent.

    classJedi{constructor(options){options||(options={});varlightsaber=options.lightsaber||'blue';this.set('lightsaber',lightsaber);}set(key,val){this[key]=val;}get(key){returnthis[key];}}

    ↑ Back to top

  • (ES6) Use the class syntax instead of constructor functions and prototypes

    // oldfunctionJedi(options){ForceUser.call(this);this.name=options.name;}Jedi.prototype=Object.create(ForceUser);Jedi.prototype.jump=functionjump(){this.jumping=true;}// preferredclassJedi : ForceUser{constructor(options){this.name=options.name;}jump(){this.jumping=true;}}
  • Methods can return this to help with method chaining.

    // badclassJedi{jump(){this.jumping=true;returntrue;}setHeight(height){this.height=height;}}letluke=newJedi();luke.jump();// => trueluke.setHeight(20)// => undefined// goodclassJedi{jump(){this.jumping=true;returnthis;}setHeight(height){this.height=height;returnthis;}}letluke=newJedi();luke.jump().setHeight(20);
  • It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.

    classJedi{constructor(options){options||(options={});this.name=options.name||'no name';}getName(){returnthis.name;}toString(){return'Jedi - '+this.getName();}}
  • (ES5) Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!

    functionJedi(){console.log('new jedi');}// badJedi.prototype={fight: functionfight(){console.log('fighting');},block: functionblock(){console.log('blocking');}};// goodJedi.prototype.fight=functionfight(){console.log('fighting');};Jedi.prototype.block=functionblock(){console.log('blocking');};

    ↑ Back to top

  • When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:

    // bad$(this).trigger('listingUpdated',listing.id);
    ...
    $(this).on('listingUpdated',(e,listingId)=>/* do something with listingId */);

    prefer:

    // good$(this).trigger('listingUpdated',{listingId : listing.id});
    ...
    $(this).on('listingUpdated',(e,listingId)=>/* do something with listingId */);

↑ Back to top

  • Wrap the function expression in parentheses.

  • The module should start with a ;. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. Explanation

  • The file name should match the name of the single export. Casing should follow the same rules as the export -- e.g. a module that exports a constructor should be PascalCase.

  • Add a method called noConflict() that sets the exported module to the previous version and returns this one.

  • Always declare 'use strict'; at the top of the module.

    // fancyInput/fancyInput.js;(function(global,$){'use strict';letpreviousFancyInput=global.FancyInput;functionFancyInput(options){this.options=options||{};}FancyInput.noConflict=functionnoConflict(){global.FancyInput=previousFancyInput;returnFancyInput;};global.FancyInput=FancyInput;})(window,window.jQuery);

    ↑ Back to top

  • Don't prefix jQuery object variables with a $.

    // badlet$sidebar=$('.sidebar');// goodletsidebar=$('.sidebar');
  • Cache jQuery lookups.

    // badfunctionsetSidebar(){$('.sidebar').hide();// ...stuff...$('.sidebar').css({'background-color': 'pink'});}// goodfunctionsetSidebar(){letsidebar=$('.sidebar');sidebar.hide();// ...stuff...sidebar.css({'background-color': 'pink'});}
  • For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf

  • Use find with scoped jQuery object queries.

    // bad$('ul','.sidebar').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// goodsidebar.find('ul').hide();

    ↑ Back to top

↑ Back to top

↑ Back to top

Read This

Other Styleguides

Other Styles

Further Reading

Books

Blogs

↑ Back to top

(The MIT License)

Copyright (c) 2012 Airbnb

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

↑ Back to top

};

About

JavaScript Style Guide

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Packages

Contributors