- Notifications
You must be signed in to change notification settings - Fork514
🎨 A JavaScript Quality Guide
License
bevacqua/js
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Aquality conscious andorganic JavaScript quality guide
This style guide aims to provide the ground rules for an application's JavaScript code, such that it's highly readable and consistent across different developers on a team. The focus is put on quality and coherence across the different pieces of your application.
These suggestions aren't set in stone, they aim to provide a baseline you can use in order to write more consistent codebases. To maximize effectiveness, share the styleguide among your co-workers and attempt to enforce it. Don't become obsessed about code style, as it'd be fruitless and counterproductive. Try and find the sweet spot that makes everyone in the team comfortable developing for your codebase, while not feeling frustrated that their code always fails automated style checking because they added a single space where they weren't supposed to. It's a thin line, but since it's a very personal line I'll leave it to you to do the drawing.
Use together withbevacqua/css for great good!
Feel free to fork this style guide, or better yet, sendPull Requests this way!
- Modules
- Strict Mode
- Spacing
- Semicolons
- Style Checking
- Linting
- Strings
- Variable Declaration
- Conditionals
- Equality
- Ternary Operators
- Functions
- Prototypes
- Object Literals
- Array Literals
- Regular Expressions
console
Statements- Comments
- Variable Naming
- Polyfills
- Everyday Tricks
- License
This style guide assumes you're using a module system such asCommonJS,AMD,ES6 Modules, or any other kind of module system. Modules systems provide individual scoping, avoid leaks to theglobal
object, and improve code base organization byautomating dependency graph generation, instead of having to resort to manually creating multiple<script>
tags.
Module systems also provide us with dependency injection patterns, which are crucial when it comes to testing individual components in isolation.
Always put'use strict';
at the top of your modules. Strict mode allows you to catch nonsensical behavior, discourages poor practices, andis faster because it allows compilers to make certain assumptions about your code.
Spacing must be consistent across every file in the application. To this end, using something like.editorconfig
configuration files is highly encouraged. Here are the defaults I suggest to get started with JavaScript indentation.
# editorconfig.orgroot = true[*]indent_style = spaceindent_size = 2end_of_line = lfcharset = utf-8trim_trailing_whitespace = trueinsert_final_newline = true[*.md]trim_trailing_whitespace = false
Settling for either tabs or spaces is up to the particularities of a project, but I recommend using 2 spaces for indentation. The.editorconfig
file can take care of that for us and everyone would be able to create the correct spacing by pressing the tab key.
Spacing doesn't just entail tabbing, but also the spaces before, after, and in between arguments of a function declaration. This kind of spacing istypically highly irrelevant to get right, and it'll be hard for most teams to even arrive at a scheme that will satisfy everyone.
function(){}
function(a,b){}
function(a,b){}
function(a,b){}
Try to keep these differences to a minimum, but don't put much thought to it either.
Where possible, improve readability by keeping lines below the 80-character mark.
The majority of JavaScript programmersprefer using semicolons. This choice is done to avoid potential issues with Automatic Semicolon Insertion(ASI). If you decide against using semicolons,make sure you understand the ASI rules.
Regardless of your choice, a linter should be used to catch unnecessary or unintentional semicolons.
Don't. Seriously,this is super painful for everyone involved, and no observable gain is attained from enforcing such harsh policies.
On the other hand, linting is sometimes necessary. Again, don't use a linter that's super opinionated about how the code should be styled, likejslint
is. Instead use something more lenient, likejshint
oreslint
.
A few tips when using JSHint.
- Declare a
.jshintignore
file and includenode_modules
,bower_components
, and the like - You can use a
.jshintrc
file like the one below to keep your rules together
{"curly":true,"eqeqeq":true,"newcap":true,"noarg":true,"noempty":true,"nonew":true,"sub":true,"undef":true,"unused":true,"trailing":true,"boss":true,"eqnull":true,"strict":true,"immed":true,"expr":true,"latedef":"nofunc","quotmark":"single","indent":2,"node":true}
By no means are these rules the ones you should stick to, butit's important to find the sweet spot between not linting at all and not being super obnoxious about coding style.
Strings should always be quoted using the same quotation mark. Use'
or"
consistently throughout your codebase. Ensure the team is using the same quotation mark in every portion of JavaScript that's authored.
varmessage='oh hai '+name+"!";
varmessage='oh hai '+name+'!';
Usually you'll be a happier JavaScript developer if you hack together a parameter-replacing method likeutil.format
in Node. That way it'll be far easier to format your strings, and the code looks a lot cleaner too.
varmessage=util.format('oh hai %s!',name);
You could implement something similar using the piece of code below.
functionformat(){varargs=[].slice.call(arguments);varinitial=args.shift();functionreplacer(text,replacement){returntext.replace('%s',replacement);}returnargs.reduce(replacer,initial);}
To declare multi-line strings, particularly when talking about HTML snippets, it's sometimes best to use an array as a buffer and then join its parts. The string concatenating style may be faster but it's also much harder to keep track of.
varhtml=['<div>',format('<span>%s</span>',name),'</div>'].join('');
With the array builder style, you can also push parts of the snippet and then join everything together at the end. This is in fact what somestring templating engines like Jade prefer to do.
Always declare variables ina consistent manner, and at the top of their scope. Keeping variable declarations toone per line is encouraged. Comma-first, a singlevar
statement, multiplevar
statements, it's all fine, just be consistent across the project, and ensure the team is on the same page.
varfoo=1,bar=2;varbaz;varpony;vara,b;
varfoo=1;if(foo>1){varbar=2;}
Just because they're consistent with each other, not because of the style
varfoo=1;varbar=2;varbaz;varpony;vara;varb;
varfoo=1;varbar;if(foo>1){bar=2;}
Variable declarations that aren't immediately assigned a value are acceptable to share the same line of code.
vara='a';varb=2;vari,j;
Brackets are enforced. This, together with a reasonable spacing strategy will help you avoid mistakes such asApple's SSL/TLS bug.
if(err)throwerr;
if(err){throwerr;}
It's even better if you avoid keeping conditionals on a single line, for the sake of text comprehension.
if(err){throwerr;}
Avoid using==
and!=
operators, always favor===
and!==
. These operators are called the "strict equality operators," whiletheir counterparts will attempt to cast the operands into the same value type.
functionisEmptyString(text){returntext=='';}isEmptyString(0);// <- true
functionisEmptyString(text){returntext==='';}isEmptyString(0);// <- false
Ternary operators are fine for clear-cut conditionals, but unacceptable for confusing choices. As a rule, if you can't eye-parse it as fast as your brain can interpret the text that declares the ternary operator, chances are it's probably too complicated for its own good.
jQuery is a prime example of a codebase that'sfilled with nasty ternary operators.
functioncalculate(a,b){returna&&b ?11 :a ?10 :b ?1 :0;}
functiongetName(mobile){returnmobile ?mobile.name :'Generic Player';}
In cases that may prove confusing just useif
andelse
statements instead.
When declaring a function, always use thefunction declaration form instead offunction expressions. Becausehoisting.
varsum=function(x,y){returnx+y;};
functionsum(x,y){returnx+y;}
That being said, there's nothing wrong with function expressions that are justcurrying another function.
varplusThree=sum.bind(null,3);
Keep in mind thatfunction declarations will be hoisted to the top of the scope so it doesn't matter the order they are declared in. That being said, you should always keep functions at the top level in a scope, and avoid placing them inside conditional statements.
if(Math.random()>0.5){sum(1,3);functionsum(x,y){returnx+y;}}
if(Math.random()>0.5){sum(1,3);}functionsum(x,y){returnx+y;}
functionsum(x,y){returnx+y;}if(Math.random()>0.5){sum(1,3);}
If you need a"no-op" method you can use eitherFunction.prototype
, orfunction noop () {}
. Ideally a single reference tonoop
is used throughout the application.
Whenever you have to manipulate an array-like object, cast it to an array.
vardivs=document.querySelectorAll('div');for(i=0;i<divs.length;i++){console.log(divs[i].innerHTML);}
vardivs=document.querySelectorAll('div');[].slice.call(divs).forEach(function(div){console.log(div.innerHTML);});
However, be aware that there is asubstantial performance hit in V8 environments when using this approach onarguments
. If performance is a major concern, avoid castingarguments
withslice
and instead use afor
loop.
varargs=[].slice.call(arguments);
vari;varargs=newArray(arguments.length);for(i=0;i<args.length;i++){args[i]=arguments[i];}
Don't declare functions inside of loops.
varvalues=[1,2,3];vari;for(i=0;i<values.length;i++){setTimeout(function(){console.log(values[i]);},1000*i);}
varvalues=[1,2,3];vari;for(i=0;i<values.length;i++){setTimeout(function(i){returnfunction(){console.log(values[i]);};}(i),1000*i);}
varvalues=[1,2,3];vari;for(i=0;i<values.length;i++){setTimeout(function(i){console.log(values[i]);},1000*i,i);}
varvalues=[1,2,3];vari;for(i=0;i<values.length;i++){wait(i);}functionwait(i){setTimeout(function(){console.log(values[i]);},1000*i);}
Or even better, just use.forEach
which doesn't have the same caveats as declaring functions infor
loops.
[1,2,3].forEach(function(value,i){setTimeout(function(){console.log(value);},1000*i);});
Whenever a method is non-trivial, make the effort touse a named function declaration rather than an anonymous function. This will make it easier to pinpoint the root cause of an exception when analyzing stack traces.
functiononce(fn){varran=false;returnfunction(){if(ran){return};ran=true;fn.apply(this,arguments);};}
functiononce(fn){varran=false;returnfunctionrun(){if(ran){return};ran=true;fn.apply(this,arguments);};}
Avoid keeping indentation levels from raising more than necessary by using guard clauses instead of flowingif
statements.
if(car){if(black){if(turbine){return'batman!';}}}
if(condition){// 10+ lines of code}
if(!car){return;}if(!black){return;}if(!turbine){return;}return'batman!';
if(!condition){return;}// 10+ lines of code
Hacking native prototypes should be avoided at all costs, use a method instead. If you must extend the functionality in a native type, try using something likeposer instead.
String.prototype.half=function(){returnthis.substr(0,this.length/2);};
functionhalf(text){returntext.substr(0,text.length/2);}
Avoid prototypical inheritance models unless you have a very goodperformance reason to justify yourself.
- Prototypical inheritance boosts puts need for
this
through the roof - It's way more verbose than using plain objects
- It causes headaches when creating
new
objects - Needs a closure to hide valuable private state of instances
- Just use plain objects instead
Instantiate using the egyptian notation{}
. Use factories instead of constructors, here's a proposed pattern for you to implement objects in general.
functionutil(options){// private methods and state go herevarfoo;functionadd(){returnfoo++;}functionreset(){// note that this method isn't publicly exposedfoo=options.start||0;}reset();return{// public interface methods go hereuuid:add};}
Instantiate using the square bracketed notation[]
. If you have to declare a fixed-dimension array for performance reasons then it's fine to use thenew Array(length)
notation instead.
It's about time you master array manipulation!Learn about the basics. It's way easier than you might think.
Learn and abuse the functional collection manipulation methods. These areso worth the trouble.
Keep regular expressions in variables, don't use them inline. This will vastly improve readability.
if(/\d+/.test(text)){console.log('so many numbers!');}
varnumeric=/\d+/;if(numeric.test(text)){console.log('so many numbers!');}
Alsolearn how to write regular expressions, and what they actually do. Then you can alsovisualize them online.
Preferably bakeconsole
statements into a service that can easily be disabled in production. Alternatively, don't ship anyconsole.log
printing statements to production distributions.
Commentsaren't meant to explain what the code does. Goodcode is supposed to be self-explanatory. If you're thinking of writing a comment to explain what a piece of code does, chances are you need to change the code itself. The exception to that rule is explaining what a regular expression does. Good comments are supposed toexplain why code does something that may not seem to have a clear-cut purpose.
// create the centered containervarp=$('<p/>');p.center(div);p.text('foo');
varcontainer=$('<p/>');varcontents='foo';container.center(parent);container.text(contents);megaphone.on('data',function(value){container.text(value);// the megaphone periodically emits updates for container});
varnumeric=/\d+/;// one or more digits somewhere in the stringif(numeric.test(text)){console.log('so many numbers!');}
Commenting out entire blocks of codeshould be avoided entirely, that's why you have version control systems in place!
Variables must have meaningful names so that you don't have to resort to commenting what a piece of functionality does. Instead, try to be expressive while succinct, and use meaningful variable names.
functiona(x,y,z){returnz*y/x;}a(4,2,6);// <- 3
functionruleOfThree(had,got,have){returnhave*got/had;}ruleOfThree(4,2,6);// <- 3
Where possible use the native browser implementation and includea polyfill that provides that behavior for unsupported browsers. This makes the code easier to work with and less involved in hackery to make things just work.
If you can't patch a piece of functionality with a polyfill, thenwrap all uses of the patching code in a globally available method that is accessible from everywhere in the application.
Use||
to define a default value. If the left-hand value isfalsy then the right-hand value will be used. Be advised, that because of loose type comparison, inputs likefalse
,0
,null
or''
will be evaluated as falsy, and converted to default value. For strict type checking useif (value === void 0) { value = defaultValue }
.
functiona(value){vardefaultValue=33;varused=value||defaultValue;}
Use.bind
topartially-apply functions.
functionsum(a,b){returna+b;}varaddSeven=sum.bind(null,7);addSeven(6);// <- 13
UseArray.prototype.slice.call
to cast array-like objects to true arrays.
varargs=Array.prototype.slice.call(arguments);
Useevent emitters on all the things!
varemitter=contra.emitter();body.addEventListener('click',function(){emitter.emit('click',e.target);});emitter.on('click',function(elem){console.log(elem);});// simulate clickemitter.emit('click',document.body);
UseFunction()
as a"no-op".
function(cb){setTimeout(cb||Function(),2000);}
MIT
Fork away!
About
🎨 A JavaScript Quality Guide
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors11
Uh oh!
There was an error while loading.Please reload this page.