• Stars
    star
    2,874
  • Rank 15,785 (Top 0.4 %)
  • Language
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🎨 A JavaScript Quality Guide

function qualityGuide () {

A quality conscious and organic 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.

Goal

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 with bevacqua/css for great good!

Feel free to fork this style guide, or better yet, send Pull Requests this way!

Table of Contents

  1. Modules
  2. Strict Mode
  3. Spacing
  4. Semicolons
  5. Style Checking
  6. Linting
  7. Strings
  8. Variable Declaration
  9. Conditionals
  10. Equality
  11. Ternary Operators
  12. Functions
  13. Prototypes
  14. Object Literals
  15. Array Literals
  16. Regular Expressions
  17. console Statements
  18. Comments
  19. Variable Naming
  20. Polyfills
  21. Everyday Tricks
  22. License

Modules

This style guide assumes you're using a module system such as CommonJS, AMD, ES6 Modules, or any other kind of module system. Modules systems provide individual scoping, avoid leaks to the global object, and improve code base organization by automating 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.

Strict Mode

Always put 'use strict'; at the top of your modules. Strict mode allows you to catch nonsensical behavior, discourages poor practices, and is faster because it allows compilers to make certain assumptions about your code.

Spacing

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.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_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 is typically 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.

Semicolons;

The majority of JavaScript programmers prefer 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.

Style Checking

Don't. Seriously, this is super painful for everyone involved, and no observable gain is attained from enforcing such harsh policies.

Linting

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, like jslint is. Instead use something more lenient, like jshint or eslint.

A few tips when using JSHint.

  • Declare a .jshintignore file and include node_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, but it's important to find the sweet spot between not linting at all and not being super obnoxious about coding style.

Strings

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.

Bad
var message = 'oh hai ' + name + "!";
Good
var message = 'oh hai ' + name + '!';

Usually you'll be a happier JavaScript developer if you hack together a parameter-replacing method like util.format in Node. That way it'll be far easier to format your strings, and the code looks a lot cleaner too.

Better
var message = util.format('oh hai %s!', name);

You could implement something similar using the piece of code below.

function format () {
  var args = [].slice.call(arguments);
  var initial = args.shift();

  function replacer (text, replacement) {
    return text.replace('%s', replacement);
  }
  return args.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.

var html = [
  '<div>',
    format('<span class="monster">%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 some string templating engines like Jade prefer to do.

Variable Declaration

Always declare variables in a consistent manner, and at the top of their scope. Keeping variable declarations to one per line is encouraged. Comma-first, a single var statement, multiple var statements, it's all fine, just be consistent across the project, and ensure the team is on the same page.

Bad
var foo = 1,
    bar = 2;

var baz;
var pony;

var a
  , b;
var foo = 1;

if (foo > 1) {
  var bar = 2;
}
Good

Just because they're consistent with each other, not because of the style

var foo = 1;
var bar = 2;

var baz;
var pony;

var a;
var b;
var foo = 1;
var bar;

if (foo > 1) {
  bar = 2;
}

Variable declarations that aren't immediately assigned a value are acceptable to share the same line of code.

Acceptable
var a = 'a';
var b = 2;
var i, j;

Conditionals

Brackets are enforced. This, together with a reasonable spacing strategy will help you avoid mistakes such as Apple's SSL/TLS bug.

Bad
if (err) throw err;
Good
if (err) { throw err; }

It's even better if you avoid keeping conditionals on a single line, for the sake of text comprehension.

Better
if (err) {
  throw err;
}

Equality

Avoid using == and != operators, always favor === and !==. These operators are called the "strict equality operators," while their counterparts will attempt to cast the operands into the same value type.

Bad
function isEmptyString (text) {
  return text == '';
}

isEmptyString(0);
// <- true
Good
function isEmptyString (text) {
  return text === '';
}

isEmptyString(0);
// <- false

Ternary Operators

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's filled with nasty ternary operators.

Bad
function calculate (a, b) {
  return a && b ? 11 : a ? 10 : b ? 1 : 0;
}
Good
function getName (mobile) {
  return mobile ? mobile.name : 'Generic Player';
}

In cases that may prove confusing just use if and else statements instead.

Functions

When declaring a function, always use the function declaration form instead of function expressions. Because hoisting.

Bad
var sum = function (x, y) {
  return x + y;
};
Good
function sum (x, y) {
  return x + y;
}

That being said, there's nothing wrong with function expressions that are just currying another function.

Good
var plusThree = sum.bind(null, 3);

Keep in mind that function 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.

Bad
if (Math.random() > 0.5) {
  sum(1, 3);

  function sum (x, y) {
    return x + y;
  }
}
Good
if (Math.random() > 0.5) {
  sum(1, 3);
}

function sum (x, y) {
  return x + y;
}
function sum (x, y) {
  return x + y;
}

if (Math.random() > 0.5) {
  sum(1, 3);
}

If you need a "no-op" method you can use either Function.prototype, or function noop () {}. Ideally a single reference to noop is used throughout the application.

Whenever you have to manipulate an array-like object, cast it to an array.

Bad
var divs = document.querySelectorAll('div');

for (i = 0; i < divs.length; i++) {
  console.log(divs[i].innerHTML);
}
Good
var divs = document.querySelectorAll('div');

[].slice.call(divs).forEach(function (div) {
  console.log(div.innerHTML);
});

However, be aware that there is a substantial performance hit in V8 environments when using this approach on arguments. If performance is a major concern, avoid casting arguments with slice and instead use a for loop.

Bad

var args = [].slice.call(arguments);

Good

var i;
var args = new Array(arguments.length);
for (i = 0; i < args.length; i++) {
    args[i] = arguments[i];
}

Don't declare functions inside of loops.

Bad
var values = [1, 2, 3];
var i;

for (i = 0; i < values.length; i++) {
  setTimeout(function () {
    console.log(values[i]);
  }, 1000 * i);
}
var values = [1, 2, 3];
var i;

for (i = 0; i < values.length; i++) {
  setTimeout(function (i) {
    return function () {
      console.log(values[i]);
    };
  }(i), 1000 * i);
}
Good
var values = [1, 2, 3];
var i;

for (i = 0; i < values.length; i++) {
  setTimeout(function (i) {
    console.log(values[i]);
  }, 1000 * i, i);
}
var values = [1, 2, 3];
var i;

for (i = 0; i < values.length; i++) {
  wait(i);
}

function wait (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 in for loops.

Better
[1, 2, 3].forEach(function (value, i) {
  setTimeout(function () {
    console.log(value);
  }, 1000 * i);
});

Whenever a method is non-trivial, make the effort to use 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.

Bad
function once (fn) {
  var ran = false;
  return function () {
    if (ran) { return };
    ran = true;
    fn.apply(this, arguments);
  };
}
Good
function once (fn) {
  var ran = false;
  return function run () {
    if (ran) { return };
    ran = true;
    fn.apply(this, arguments);
  };
}

Avoid keeping indentation levels from raising more than necessary by using guard clauses instead of flowing if statements.

Bad
if (car) {
  if (black) {
    if (turbine) {
      return 'batman!';
    }
  }
}
if (condition) {
  // 10+ lines of code
}
Good
if (!car) {
  return;
}
if (!black) {
  return;
}
if (!turbine) {
  return;
}
return 'batman!';
if (!condition) {
  return;
}
// 10+ lines of code

Prototypes

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 like poser instead.

Bad
String.prototype.half = function () {
  return this.substr(0, this.length / 2);
};
Good
function half (text) {
  return text.substr(0, text.length / 2);
}

Avoid prototypical inheritance models unless you have a very good performance 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

Object Literals

Instantiate using the egyptian notation {}. Use factories instead of constructors, here's a proposed pattern for you to implement objects in general.

function util (options) {
  // private methods and state go here
  var foo;

  function add () {
    return foo++;
  }

  function reset () { // note that this method isn't publicly exposed
    foo = options.start || 0;
  }

  reset();

  return {
    // public interface methods go here
    uuid: add
  };
}

Array Literals

Instantiate using the square bracketed notation []. If you have to declare a fixed-dimension array for performance reasons then it's fine to use the new 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 are so worth the trouble.

Regular Expressions

Keep regular expressions in variables, don't use them inline. This will vastly improve readability.

Bad
if (/\d+/.test(text)) {
  console.log('so many numbers!');
}
Good
var numeric = /\d+/;
if (numeric.test(text)) {
  console.log('so many numbers!');
}

Also learn how to write regular expressions, and what they actually do. Then you can also visualize them online.

console statements

Preferably bake console statements into a service that can easily be disabled in production. Alternatively, don't ship any console.log printing statements to production distributions.

Comments

Comments aren't meant to explain what the code does. Good code 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 to explain why code does something that may not seem to have a clear-cut purpose.

Bad
// create the centered container
var p = $('<p/>');
p.center(div);
p.text('foo');
Good
var container = $('<p/>');
var contents = 'foo';
container.center(parent);
container.text(contents);
megaphone.on('data', function (value) {
  container.text(value); // the megaphone periodically emits updates for container
});
var numeric = /\d+/; // one or more digits somewhere in the string
if (numeric.test(text)) {
  console.log('so many numbers!');
}

Commenting out entire blocks of code should be avoided entirely, that's why you have version control systems in place!

Variable Naming

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.

Bad
function a (x, y, z) {
  return z * y / x;
}
a(4, 2, 6);
// <- 3
Good
function ruleOfThree (had, got, have) {
  return have * got / had;
}
ruleOfThree(4, 2, 6);
// <- 3

Polyfills

Where possible use the native browser implementation and include a 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, then wrap all uses of the patching code in a globally available method that is accessible from everywhere in the application.

Everyday Tricks

Use || to define a default value. If the left-hand value is falsy then the right-hand value will be used. Be advised, that because of loose type comparison, inputs like false, 0, null or '' will be evaluated as falsy, and converted to default value. For strict type checking use if (value === void 0) { value = defaultValue }.

function a (value) {
  var defaultValue = 33;
  var used = value || defaultValue;
}

Use .bind to partially-apply functions.

function sum (a, b) {
  return a + b;
}

var addSeven = sum.bind(null, 7);

addSeven(6);
// <- 13

Use Array.prototype.slice.call to cast array-like objects to true arrays.

var args = Array.prototype.slice.call(arguments);

Use event emitters on all the things!

var emitter = contra.emitter();

body.addEventListener('click', function () {
  emitter.emit('click', e.target);
});

emitter.on('click', function (elem) {
  console.log(elem);
});

// simulate click
emitter.emit('click', document.body);

Use Function() as a "no-op".

function (cb) {
  setTimeout(cb || Function(), 2000);
}

License

MIT

Fork away!

}

More Repositories

1

dragula

👌 Drag and drop so simple it hurts
JavaScript
21,936
star
2

es6

🌟 ES6 Overview in 350 Bullet Points
4,328
star
3

rome

📆 Customizable date (and time) picker. Opt-in UI, no jQuery!
JavaScript
2,913
star
4

fuzzysearch

🔮 Tiny and blazing-fast fuzzy search in JavaScript
JavaScript
2,711
star
5

woofmark

🐕 Barking up the DOM tree. A modular, progressive, and beautiful Markdown and HTML editor
JavaScript
1,624
star
6

promisees

📨 Promise visualization playground for the adventurous
JavaScript
1,199
star
7

horsey

🐴 Progressive and customizable autocomplete component
JavaScript
1,167
star
8

css

🎨 CSS: The Good Parts
992
star
9

react-dragula

👌 Drag and drop so simple it hurts
JavaScript
992
star
10

contra

🏄 Asynchronous flow control with a functional taste to it
JavaScript
771
star
11

shots

🔫 pull down the entire Internet into a single animated gif.
JavaScript
728
star
12

insignia

🔖 Customizable tag input. Progressive. No non-sense!
JavaScript
674
star
13

campaign

💌 Compose responsive email templates easily, fill them with models, and send them out.
JavaScript
641
star
14

perfschool

🌊 Navigate the #perfmatters salt marsh waters in this NodeSchool workshopper
CSS
630
star
15

local-storage

🛅 A simplified localStorage API that just works
JavaScript
523
star
16

angularjs-dragula

👌 Drag and drop so simple it hurts
HTML
509
star
17

reads

📚 A list of physical books I own and read
486
star
18

insane

😾 Lean and configurable whitelist-oriented HTML sanitizer
JavaScript
449
star
19

hget

👏 Render websites in plain text from your terminal
HTML
334
star
20

hit-that

✊ Render beautiful pixel perfect representations of websites in your terminal
JavaScript
332
star
21

hash-sum

🎊 Blazing fast unique hash generator
JavaScript
301
star
22

swivel

Message passing between ServiceWorker and pages made simple
JavaScript
294
star
23

dominus

💉 Lean DOM Manipulation
JavaScript
277
star
24

trunc-html

📐 truncate html by text length
JavaScript
220
star
25

grunt-ec2

📦 Create, deploy to, and shutdown Amazon EC2 instances
JavaScript
190
star
26

beautify-text

✒️ Automated typographic quotation and punctuation marks
JavaScript
186
star
27

sixflix

🎬 Detects whether a host environment supports ES6. Algorithm by Netflix.
JavaScript
175
star
28

twitter-for-github

🐥 Twitter handles for GitHub
JavaScript
146
star
29

awesome-badges

🏆 Awesome, badges!
JavaScript
124
star
30

prop-tc39

Scraping microservice for TC39 proposals 😸
JavaScript
108
star
31

megamark

😻 Markdown with easy tokenization, a fast highlighter, and a lean HTML sanitizer
JavaScript
104
star
32

diferente

User-friendly virtual DOM diffing
JavaScript
95
star
33

domador

😼 Dependency-free and lean DOM parser that outputs Markdown
JavaScript
86
star
34

proposal-undefined-coalescing-operator

Undefined Coalescing Operator proposal for ECMAScript
77
star
35

dotfiles

💠 Yay! @bevacqua does dotfiles \o/
Shell
75
star
36

assignment

😿 Assign property objects onto other objects, recursively
JavaScript
73
star
37

sektor

📍 A slim alternative to jQuery's Sizzle
JavaScript
65
star
38

map-tag

🏷 Map template literal expression interpolations with ease.
JavaScript
65
star
39

unbox

Unbox a node application with a well-designed build-oriented approach in minutes
JavaScript
61
star
40

hint

Awesome tooltips at your fingertips
JavaScript
60
star
41

but

🛰 But expands your functional horizons to the edge of the universe
JavaScript
59
star
42

kanye

Smash your keyboards with ease
JavaScript
55
star
43

correcthorse

See XKCD for reference
JavaScript
52
star
44

easymap

🗺 simplified use of Google Maps API to render a bunch of markers.
JavaScript
52
star
45

flickr-cats

A demo page using the Flickr API, ServiceWorker, and plain JavaScript
HTML
49
star
46

hubby

👨 Hubby is a lowly attempt to describe public GitHub activity in natural language
JavaScript
46
star
47

ruta3

Route matcher devised for shared rendering JavaScript applications
JavaScript
45
star
48

poser

📯 Create clean arrays, or anything else, which you can safely extend
JavaScript
45
star
49

baal

🐳 Automated, autoscaled, zero-downtime, immutable deployments using plain old bash, Packer, nginx, Node.js, and AWS. Made easy.
Shell
44
star
50

lipstick

💄 sticky sessions for Node.js clustering done responsibly
JavaScript
43
star
51

crossvent

🌏 Cross-platform browser event handling
JavaScript
41
star
52

lazyjs

The minimalist JavaScript loader
JavaScript
39
star
53

spritesmith-cli

😳 Adds a CLI to the spritesmith module
JavaScript
38
star
54

gulp-jsfuck

Fuck JavaScript and obfuscate it using only 6 characters ()+[]!
JavaScript
37
star
55

measly

A measly wrapper around XHR to help you contain your requests
JavaScript
36
star
56

keynote-extractor

🎁 Extract Keynote presentations to JSON and Markdown using a simple script.
AppleScript
35
star
57

hyperterm-working-directory

🖥👷📂 Adds a default working directory setting. Opens new tabs using that working directory.
JavaScript
34
star
58

gitcanvas

🏛 Use your GitHub account's commit history as a canvas. Express the artist in you!
JavaScript
34
star
59

cave

Remove critical CSS from your stylesheet after inlining it in your pages
JavaScript
33
star
60

scrape-metadata

📜 HTML metadata scraper
JavaScript
31
star
61

feeds

🍎 RSS feeds I follow and maintain
31
star
62

suchjs

Provides essential jQuery-like methods for your evergreen browser, in under 200 lines of code. Such small.
JavaScript
30
star
63

ponyedit

An interface between contentEditable and your UI
JavaScript
29
star
64

grunt-grunt

Spawn Grunt tasks in other Gruntfiles easily from a Grunt task
JavaScript
29
star
65

ultramarked

Marked with built-in syntax highlighting and input sanitizing that doesn't encode all HTML.
JavaScript
28
star
66

sell

💰 Cross-browser text input selection made simple
JavaScript
28
star
67

icons

Free icon sets gathered around the open web
27
star
68

insert-rule

Insert rules into a stylesheet programatically with a simple API
JavaScript
26
star
69

hose

Redirect any domain to localhost for convenience or productivity!
JavaScript
26
star
70

ponymark

Next-generation PageDown fork
JavaScript
25
star
71

omnibox

Fast url parsing with a tiny footprint and extensive browser support
JavaScript
25
star
72

estimate

Calculate remaining reading time estimates in real-time
JavaScript
24
star
73

node-emoji-random

Creates a random emoji string. This is as useless as it gets.
JavaScript
24
star
74

sluggish

🐍 Sluggish slug generator that works universally
JavaScript
24
star
75

seleccion

💵 A getSelection polyfill and a setSelection ranch dressing
JavaScript
24
star
76

bullseye

🎯 Attach elements onto their target
JavaScript
23
star
77

vectorcam

🎥 Record gifs out of <svg> elements painlessly
JavaScript
22
star
78

paqui

Dead simple, packager-agnostic package management solution for front-end component developers
JavaScript
22
star
79

grunt-ngdoc

Grunt task for generating documentation using AngularJS' @ngdoc comments
JavaScript
20
star
80

ftco

⚡ Browser extension that unshortens t.co links in TweetDeck and Twitter
JavaScript
19
star
81

jadum

💍 A lean Jade compiler that understands Browserify and reuses partials
JavaScript
19
star
82

trunc-text

📏 truncate text by length, doesn't cut words
JavaScript
16
star
83

flexarea

Pretty flexible areas!
JavaScript
16
star
84

music-manager

📻 Manages a list of favorite artists and opens playlists on youtube.
JavaScript
16
star
85

grunt-integration

Run Integration Tests using Selenium, Mocha, a Server, and a Browser
JavaScript
15
star
86

apartment

🏡 Remove undesirable properties from a piece of css
JavaScript
14
star
87

mongotape

Run integration tests using mongoose and tape
JavaScript
14
star
88

rehearsal

Persist standard input to a file, then simulate real-time program execution.
JavaScript
13
star
89

queso

Turn a plain object into a query string
JavaScript
13
star
90

bitfin

🏦 Finance utility for Bitstamp
JavaScript
13
star
91

pandora-box

🐼 What will it be?
JavaScript
12
star
92

grunt-spriting-example

An example on how to seamlessly use spritesheets with Grunt.
12
star
93

artists

🎤 Big list of artists pulled from Wikipedia.
JavaScript
11
star
94

twitter-leads

🐦 Pull list of leads from a Twitter Ads Lead Generation Card
JavaScript
11
star
95

reaver

Minimal asset hashing CLI and API
JavaScript
11
star
96

atoa

Creates a true array based on `arraylike`, starting at `startIndex`.
JavaScript
10
star
97

BridgeStack

.NET StackExchange API v2.0 client library wrapper
C#
10
star
98

ama

📖 A repository to ask @bevacqua anything.
10
star
99

virtual-host

Create virtual, self-contained `connect` or `express` applications using a very simple API.
JavaScript
10
star
100

banksy

🌇 Street art between woofmark and horsey
JavaScript
10
star