Home

Awesome

Pragmatic.js code style guidelines

TL;DR

General coding:

Functions:

Statements & expressions:

Pragmatic JavaScript

The word pragmatic means "Practical, concerned with making decisions and actions that are useful in practice, not just theory."1 Writing pragmatic JavaScript is all about optimizing the process of writing JavaScript for you as a programmer, using all the facilities the language provides.

Writing less code is good; emphasized by the no optional semicolons rule, by no curly braces where not necessary and by using functional programming constructs whereever possible.

At the same time, when you come back to your code later, you want to understand it— thus long, descriptive variable and method names, and comments where necessary.

JavaScript is a modern, flexible and malleable scripting language, and it deserves to be treated as such. Pragmatic.js is also about discovering and learning the language strengths as well as its quirks so you can make full use of it.

Examples

Here are some examples from Zepto.js.

// typical helper function
function eachEvent(events, fn, iterator){
  if ($.isObject(events)) $.each(events, iterator)
  else events.split(/\s/).forEach(function(type){ iterator(type, fn) })
}

// shortcut methods for `.bind(event, fn)` for each event type
;('focusin focusout load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
  $.fn[event] = function(callback){ return this.bind(event, callback) }
})

// from Zepto core, $.fn.siblings implementation
function filtered(nodes, selector) {
  return selector === undefined ? $(nodes) : $(nodes).filter(selector)
}

$.fn.siblings = function(selector){
  return filtered(this.map(function(i, el){
    return slice.call(el.parentNode.children).filter(function(child){ return child!==el })
  }), selector)
}

Contribute

I welcome contributions—this guide is very basic at the moment and should probably have some more guidelines for specific situations and how to get started. You know where the fork & pull request buttons are.

License

Pragmatic.js is licensed under the terms of the MIT License.