This styleguide is a guideline for a uniform design of our JavaScript files.
- Modules are enclosed parts of the JavaScript
- All dependencies are provided as parameters
- A public init()-method initializes the module
- Names are written in camelCase
- The module contains an export variable named by the module
(function (tappProject, chayns, window, undefined) {
'use strict';
tappProject.init = function init(data) {
// start
};
// content
})((window.tappProject = {}), chayns, window);
(window.tappProject = {}) would overwrite an existing module. To extend an existing module you can simply use (window.tappProject = window.tappProject || {}).
(function (tappProject, chayns, window, undefined) {
'use strict';
var newFeature = {};
tappProject.awesomeFeature = newFeature;
})((window.tappProject), chayns, window);
Modules can be created in the following ways as well
var tappProject = (function (chayns, window, undefined) {
'use strict';
var tappProject;
tappProject.init = function init(data) {
// start
};
// content
return tappProject;
})(chayns, window);
var tappProject = (function (chayns, window, undefined) {
'use strict';
function init(data) {
// start
};
// content
return {
init: init
};
})(chayns, window);
- Only declared at the beginning of a file
- Explicit declaration to prevent global variables
- Should be available only in their specific modules
- Use camelCase for namings
- DOM element variables start with a leading $
(function (tappProject, chayns, $, window, undefined) {
// external variables
tappProject.debug = false;
// internal variables
var $contentBox, $introBox;
var userData;
})((window.tappProject = {}), chayns, jQuery, window);
- Prevent public functions
- Add events in the init()-function
- Namings in camelCase
(function (tappProject, chayns, $, window, undefined) {
// external functions
tappProject.openPage = function openPage(url) {
};
// internal functions
function doSomething(data) {
}
})((window.tappProject = {}), chayns, jQuery, window);
Consequent usage of english language
By using 'use strict'; some errors JavaScript usually would not throw an exception for, become normal erros. This helps in preventing errors early on.
Strings are declared in single quotes.
// good
var text = 'string';
// bad
var text = "string";
Prefer type secure comparisons.
'0' == 0; // true
0 == 0; // true
'0' === 0; // false
0 === 0; // true
'0' != 0; // false
'0' !== 0; // true
null == undefined; // true
null === undefined; // false
Every level is indented using tabs. In the IDE's any developer decides for himself how to display the tab indents.
No breaks before opening curled braces.
if(true) {
} else {
}
function name(param) {
}
Use a semicolon behind allocations and directly called functions.
var x = 'content';
var fn = function() {
// do stuff
};
(function(data) {
})('data');