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.

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.

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

Clone this wiki locally