JavaScript Styleguide
Guidelines for writing JavaScript code at sgalinski Internet Services
Formal Rules
- Don't include javascript files written in CommonJS in you FLUID files. Only via TypoScript that can be easily overwritten or better as an inclusion in the project main.js file.
- All comments / namings are in english language.
- Indentations are done with the tab character.
- The first character within a comment must be a space.
- The opening curly brace of a function definition is not on a new line.
- Use JsDoc Style for documentation.
- Use one new line to separate blocks.
- The function description is followed by a blank line.
- Tip: Configure your editor to use a JsHint Linter.
- Linting errors from the Toolchain console need to be fixed. Ask your teammates if you don’t know how.
- A .jshintrc file is provided by every project. You can always find the latest version in our Toolchain generator.
- Do not use eval!
- Don’t use the function constructor, don’t pass Strings to setTimeout and setInterval!
- Wrap immediately called function expressions inside parentheses.
- Don’t use the global namespace, write CommonJS modules instead.
- If you have to deal with code that uses the global namespace, make sure to access it through the window object to make it clear that you are referring to a global variable.
/**
* This is a dummy function block
*
* @param {Number} dummyId A dummy ID
* @param {Object} dummyConfig The configuration data for this function
* @return {void}
*/
function dummyFunction(dummyId, dummyConfig) {
}
Basic Rules
- Always use the strict mode!
- Use promises instead of callback functions when possible. Your code will become much more readable.
- Use the console API for debugging. But make sure to delete your debug logs before committing your code. No one wants to have their console spammed with useless logs.
- Rule of thumb: Be careful with syntactical hacks. JavaScript is a very forgiving language and allows some pretty nasty constructs. Always ask yourself if the benefit of such hacks is worth having your co-workers not understanding your code. Make sure to comment your code if you have to do uncommon things.
‘use strict’;
// example with callbacks
asyncCall(‘someSource’, function(err, data) {
if (err) handleError(err);
asyncCall(‘someSource’, function(err, data) {
if (err) handleError(err);
handleSuccess(data);
});
});
// example with promises
asyncCall(‘someSource’).then(function() {
return asyncCall(‘someSource’);
}).then(handleSuccess)
.fail(handleError)
.done();
Common Architecture
- We use CommonJs via Browserify to achieve modularity in our code.
- A module must do one thing and one thing well. This enforces reusability and keeps the code maintainable.
- External dependencies are managed via NPM.
- Do not duplicate modules. If there already is a loading-spinner module, extend it instead of creating a second one!
- jQuery is a helper, not a framework or an architectural tool.
- Rich Web Applications are built with AngularJS, which uses jQuery as a helper library.
See http://gitlab.sgalinski.de/snippets/16 for a CommonJS example module
Separation of concerns
- Do NOT set CSS styles via JavaScript. That’s what CSS files are for.
- Even setting the display property via JS is not a clever idea as this causes some animations to fail. (e.g. display: none could eventually needed to be changed to visibility: hidden)
- If your JavaScript alters the view, apply a class name. In this case you probably want to set a certain UI state.
- show, hide, fadeIn, fadeOut and other methods known from jQuery are ok to use. Keep in mind that those functions set display:block for visible elements, though. This will cause issues for elements that need to be displayed as inline-block, or flex!
Anonymous Sections
- Avoid usage of anonymous functions if the code is used often or if it’s larger than 5 lines of code to keep it maintainable. Don’t use anonymous functions in loops as this causes performance issues.
- Alternative: Use named functions instead.
- An anonymous function has to become a named function as soon as its logic is used at two different places.
- Do NOT duplicate code.
Naming Conventions
- Variable names are written in lower CamelCase.
- Module names are written in upper CamelCase.
- A variable that holds a jQuery wrapped object has to be prefixed with a $-sign.
- Constructor parameters are prefixed with an underscore.
var someRandomVariable = ‘foo’,
var SomeModule = [...] // new SomeModule()
var $ctaButton = $(‘#cta-button’);
var myObj = function(_param) {
...
};
Code Style
- Variable declarations are the first thing within a block.
- Use only one var statement for the whole declaration block.
- Always use typesafe comparisons (using === / !==).
- Use the typoeof operator to do type comparisons:
- typeof myVar === ‘undefined’
- One .js file only contains one module.
var firstVariable = ‘foo’,
secondVariable;