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.

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.

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()...

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 ==.

Clone this wiki locally