Skip to content

JS Guidelines

Elisabeth Hamel edited this page Jan 18, 2017 · 20 revisions

The examples are written in jQuery but the guidelines are also valid in VanillaJS.

General

  • Write self-explanatory code. You should know what a function does by reading its name.
  • When your code get more complex: comment!
  • Don't use new Object (use [] for an array, {} for an object...)
  • Don't create DOM elements within a loop

Bad

for(var i = 0; i < 7; i++;){
    $('body').append('div');
}

Good

var i = 0, divElts = '';
for(i; i < 7; i++){
    divElts .= '<div></div>';
}
$('body').append(divElts);
  • Chain things:

Bad

$('body').addClass('hello');
$('body').append('Hello!');

Good

$('body').addClass('hello').append('Hello!'); 
  • DRY

Bad

$('.btn').on('click', function(){
    // Do stuff
});
$('.link').on('click', function(){
    // Do the same stuff
});

Good

function doStuff(){
    // Just do it!
}
$('.btn, .link').on('click', doStuff);

Formatting

Use camelCase for naming you variables and functions;

Selectors

Use IDs to select elements used in JS. This is better for performance and as we are not using IDs in CSS, it allows us to see directly in the HTML which elements are used in JS.

If you must use a class, add a specific class not used in CSS with the "js-" prefix.

Avoid excessive specificity: https://learn.jquery.com/performance/optimize-selectors/

Prefer the use of the find() function.

If you are using the same selector several times, keep it in a variable.

Bad

$('#list li a');

Better

$('#list a');

Good

$('#list').find('a');

Events binding

In jQuery, prefer the on() function to bind events, rather than click(), hover()...

Use e.preventDefault() instead of return false.

Try to delegate all your events binding: https://learn.jquery.com/events/event-delegation/

Bad

$('li').on('click', function(){
    // do something
});

Good

$('#list').on('click', 'li', function(){
    // do something
});

Loops

Try to use the map(), filter(), reduce() functions instead of loops: http://cryto.net/~joepie91/blog/2015/05/04/functional-programming-in-javascript-map-filter-reduce/

When you have to use them, prefer the foreach (or each in jQuery) to for or while.

Functions

Declare functions before using them. Try to write small, specific and pure functions, to avoid side effects and improve readability.

http://alistapart.com/article/making-your-javascript-pure

Variables

Avoid using global variables. Always declare your variables with var (or constor let). Declare all your variables together, at the top of your files and functions.

Conditions

Always use strict condition operators like === instead of ==.

Scroll / Resize events

Use throttle()and requestAnimFrame() functions.

Clone this wiki locally