You are using an outdated browser. Please upgrade your browser to improve your experience.

Custom JavaScript
Coding Guidelines

Generate and share your own JavaScript coding guidelines

Step 1.

Define Guidelines

Step 2.

Preview & Save

Step 3.

Share & Enjoy

Indentation

Pros:

  • Tabs use only 1 character (smaller file sizes).
  • Tabs are flexible. Everyone can have different settings as to how many "spaces" a tab occupies.

Cons:

  • Tabs when viewed in browsers, always take 8 spaces.
  • Tabs are harder to use when Instant Messaging, sharing code, etc.

Pros:

  • Spaces are consistent across different software and systems.
  • Spaces are easier to use when Instant Messaging, sharing code, etc.

Cons:

  • Each space uses a character (bigger file sizes).
  • Spaces are not flexible. Everyone sees the same number of spaces for indentation, no matter their settings.

Spacing

Pros:

  • 4 Spaces allow for improved readability.

Cons:

  • 4 Spaces can make code "grow sideways" faster.
  • 4 Spaces make for bigger file sizes.

Pros:

  • 2 Spaces make code "grow sideways" slower.
  • 2 Spaces make for smaller file sizes.

Cons:

  • 2 Spaces make the code less readable.

Readability

What it means:

Basically, add extra spaces and line breaks almost everywhere (between parenthesis, array items, object properties, etc.), to make the code more readable

Example:

'use strict'; module.exports = function( PackageService, SettingService ) { return ( require('./../classes/Controller.js') ).extend( { service: PackageService }, { // Get 3 most popular packages popularAction: function() { PackageService.find({ limit: 3, order: 'views DESC' }) .then( this.proxy('send') ) .fail( this.proxy('handleException') ); }, // Create a package postAction: function() { var data = this.req.body; if ( data.id ) { return this.putAction(); } PackageService .create( data ) .then( this.proxy('send') ) .fail( this.proxy('handleException') ); }, // Update a package putAction: function() { this.send( 403, 'Updates are not allowed' ); } } ); };

What it means:

Add spaces and line breaks when/where readability gets compromised otherwise.

Example:

'use strict'; module.exports = function(PackageService, SettingService) { return (require('./../classes/Controller.js')).extend( { service: PackageService }, { // Get 3 most popular packages popularAction: function() { PackageService.find({ limit: 3, order: 'views DESC' }) .then(this.proxy('send')) .fail(this.proxy('handleException')); }, // Create a package postAction: function() { var data = this.req.body; if (data.id) { return this.putAction(); } PackageService .create(data) .then(this.proxy('send')) .fail(this.proxy('handleException')); }, // Update a package putAction: function() { this.send(403, 'Updates are not allowed'); } } ); };

Blocks

What it means:

When you're writing blocks (or array items), you start them on the same line.

Example:

define([ 'app', 'highlightjs' ], function( app, hljs ) { 'use strict'; app.controller( 'Home', [ '$scope', ... function( $scope, ... ) { // Init $scope properties // $scope helpers $scope.helpers = { ... }; // $scope data holders $scope.data = { thePackage: {}, ... }; // $scope viewer helpers $scope.viewers = { showPackageForm: function() { return $scope.helpers.packageStarted; }, showSettingHelper: function( settingId ) { if ( $scope.helpers.settingsHelpersVisible.indexOf(settingId) !== -1 ) { return true; } return false; }, showPackageStep: function( step ) { if ( step === $scope.helpers.currentStep && $scope.viewers.showPackageForm() ) { return true; } return false; } }; // Fetch popular packages PackageService.getPopular() .then( function( popularGuidelines ) { $scope.data.popularGuidelines = popularGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the popular packages. Please check your internet connection.', 'error' ); console.log( error ); }); // Fetch latest packages PackageService.getLatest() .then( function( latestGuidelines ) { $scope.data.latestGuidelines = latestGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the latest packages. Please check your internet connection.', 'error' ); console.log( error ); }); } ]); } );

What it means:

When you're writing blocks (or array items), you start them on the next line.

Beware you can't do this with the "return" expression, otherwise you'll get a syntax error.

Example:

define( [ 'app', 'highlightjs' ], function( app, hljs ) { 'use strict'; app.controller( 'Home', [ '$scope', ... function( $scope, ... ) { // Init $scope properties // $scope helpers $scope.helpers = { ... }; // $scope data holders $scope.data = { thePackage: {}, ... }; // $scope viewer helpers $scope.viewers = { showPackageForm: function() { return $scope.helpers.packageStarted; }, showSettingHelper: function( settingId ) { if ( $scope.helpers.settingsHelpersVisible.indexOf(settingId) !== -1 ) { return true; } return false; }, showPackageStep: function( step ) { if ( step === $scope.helpers.currentStep && $scope.viewers.showPackageForm() ) { return true; } return false; } }; // Fetch popular packages PackageService.getPopular() .then( function( popularGuidelines ) { $scope.data.popularGuidelines = popularGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the popular packages. Please check your internet connection.', 'error' ); console.log( error ); }); // Fetch latest packages PackageService.getLatest() .then( function( latestGuidelines ) { $scope.data.latestGuidelines = latestGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the latest packages. Please check your internet connection.', 'error' ); console.log( error ); }); } ]); } );

Variables Naming

What it means:

When writing variable names, you're not scared of variablesThatHaveALotOfCharacters.

The variable names are also descriptive of what they're doing. Not just "tmp", or "obj".

Example:

'use strict'; module.exports = function( SettingService ) { return ( require('./../classes/Controller.js') ).extend( { service: SettingService, }, { groupedAction: function() { SettingService.getSettingsGroupedAndSorted() .then( this.proxy( 'send' ) ) .fail( this.proxy( 'handleException' ) ); }, postAction: function() { var temporaryIdFromPost = 0, postedSettingObject = this.req.body; ... } }); };

What it means:

You don't write variables that are too big, but you don't like have very short variables.

The variable names are also somewhat descriptive of what they're doing. They don't require a lot of thinking about what they are.

Example:

'use strict'; module.exports = function( Service ) { return ( require('./../classes/Controller.js') ).extend( { service: Service, }, { groupedAction: function() { Service.getSettingsGroups() .then( this.proxy( 'send' ) ) .fail( this.proxy( 'handleEx' ) ); }, postAction: function() { var tmpId = 0, settingObject = this.req.body; ... } }); };

Variables Case

What it means:

Your variable names are lower_case.

Example:

define([ 'app', 'highlightjs' ], function( app, hljs ) { 'use strict'; app.controller( 'Home', [ '$scope', ... function( $scope, ... ) { // Init $scope properties // $scope helpers $scope.helpers = { ... }; // $scope data holders $scope.data = { the_package: {}, ... }; // $scope viewer helpers $scope.viewers = { show_package_form: function() { return $scope.helpers.package_started; }, show_setting_helper: function( setting_id ) { if ( $scope.helpers.settings_helpers_visible.indexOf(setting_id) !== -1 ) { return true; } return false; }, show_package_step: function( step ) { if ( step === $scope.helpers.current_step && $scope.viewers.show_package_form() ) { return true; } return false; } }; // Fetch popular packages package_service.get_popular() .then( function( popular_guidelines ) { $scope.data.popular_guidelines = popular_guidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the popular packages. Please check your internet connection.', 'error' ); console.log( error ); }); // Fetch latest packages package_service.get_latest() .then( function( latest_guidelines ) { $scope.data.latest_guidelines = latest_guidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the latest packages. Please check your internet connection.', 'error' ); console.log( error ); }); } ]); } );

What it means:

Your variable names are in camelCase.

Example:

define([ 'app', 'highlightjs' ], function( app, hljs ) { 'use strict'; app.controller( 'Home', [ '$scope', ... function( $scope, ... ) { // Init $scope properties // $scope helpers $scope.helpers = { ... }; // $scope data holders $scope.data = { thePackage: {}, ... }; // $scope viewer helpers $scope.viewers = { showPackageForm: function() { return $scope.helpers.packageStarted; }, showSettingHelper: function( settingId ) { if ( $scope.helpers.settingsHelpersVisible.indexOf(settingId) !== -1 ) { return true; } return false; }, showPackageStep: function( step ) { if ( step === $scope.helpers.currentStep && $scope.viewers.showPackageForm() ) { return true; } return false; } }; // Fetch popular packages PackageService.getPopular() .then( function( popularGuidelines ) { $scope.data.popularGuidelines = popularGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the popular packages. Please check your internet connection.', 'error' ); console.log( error ); }); // Fetch latest packages PackageService.getLatest() .then( function( latestGuidelines ) { $scope.data.latestGuidelines = latestGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the latest packages. Please check your internet connection.', 'error' ); console.log( error ); }); } ]); } );

Functions Naming

What it means:

When writing function names, you're not scared of functionNamesThatHaveALotOfCharacters.

The function names are also descriptive of what they're doing. Not just "tmp", or "obj".

Example:

'use strict'; module.exports = function( SettingService ) { return ( require('./../classes/Controller.js') ).extend( { service: SettingService, }, { groupedAction: function() { SettingService.getSettingsGroupedAndSorted() .then( this.proxy( 'send' ) ) .fail( this.proxy( 'handleException' ) ); }, postAction: function() { var temporaryIdFromPost = 0, postedSettingObject = this.req.body; ... } }); };

What it means:

You don't write function names that are too big, but you don't like have very short function names.

The function names are also somewhat descriptive of what they're doing. They don't require a lot of thinking about what they are.

Example:

'use strict'; module.exports = function( Service ) { return ( require('./../classes/Controller.js') ).extend( { service: Service, }, { groupedAction: function() { Service.getSettingsGroups() .then( this.proxy( 'send' ) ) .fail( this.proxy( 'handleEx' ) ); }, postAction: function() { var tmpId = 0, settingObject = this.req.body; ... } }); };

Functions Case

What it means:

Your function names are lower_case.

Example:

define([ 'app', 'highlightjs' ], function( app, hljs ) { 'use strict'; app.controller( 'Home', [ '$scope', ... function( $scope, ... ) { // Init $scope properties // $scope helpers $scope.helpers = { ... }; // $scope data holders $scope.data = { the_package: {}, ... }; // $scope viewer helpers $scope.viewers = { show_package_form: function() { return $scope.helpers.package_started; }, show_setting_helper: function( setting_id ) { if ( $scope.helpers.settings_helpers_visible.indexOf(setting_id) !== -1 ) { return true; } return false; }, show_package_step: function( step ) { if ( step === $scope.helpers.current_step && $scope.viewers.show_package_form() ) { return true; } return false; } }; // Fetch popular packages package_service.get_popular() .then( function( popular_guidelines ) { $scope.data.popular_guidelines = popular_guidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the popular packages. Please check your internet connection.', 'error' ); console.log( error ); }); // Fetch latest packages package_service.get_latest() .then( function( latest_guidelines ) { $scope.data.latest_guidelines = latest_guidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the latest packages. Please check your internet connection.', 'error' ); console.log( error ); }); } ]); } );

What it means:

Your function names are in camelCase.

Example:

define([ 'app', 'highlightjs' ], function( app, hljs ) { 'use strict'; app.controller( 'Home', [ '$scope', ... function( $scope, ... ) { // Init $scope properties // $scope helpers $scope.helpers = { ... }; // $scope data holders $scope.data = { thePackage: {}, ... }; // $scope viewer helpers $scope.viewers = { showPackageForm: function() { return $scope.helpers.packageStarted; }, showSettingHelper: function( settingId ) { if ( $scope.helpers.settingsHelpersVisible.indexOf(settingId) !== -1 ) { return true; } return false; }, showPackageStep: function( step ) { if ( step === $scope.helpers.currentStep && $scope.viewers.showPackageForm() ) { return true; } return false; } }; // Fetch popular packages PackageService.getPopular() .then( function( popularGuidelines ) { $scope.data.popularGuidelines = popularGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the popular packages. Please check your internet connection.', 'error' ); console.log( error ); }); // Fetch latest packages PackageService.getLatest() .then( function( latestGuidelines ) { $scope.data.latestGuidelines = latestGuidelines; }, function( error ) { $scope.actions.notify( 'Oh, no! There was a problem fetching the latest packages. Please check your internet connection.', 'error' ); console.log( error ); }); } ]); } );

Comma in Variable Declaration

What it means:

When declaring variables, you use a leading comma.

Example:

'use strict'; // Get everything ready var config = require( './config' ) , express = require( 'express' ) , webPort = process.env.NODE_WWW_PORT || config.webPort || 8080 , env = process.env.NODE_ENV || config.environmentName || 'development' , initializeRoutes = require( './routes' ) , modelInjector = require( './src/utils/modelInjector' ) , Sequelize = require( 'sequelize' ) , Injector = require( './src/utils/injector' ) , passport = require( 'passport' ) , app = express(); // Setup ORM var sequelize = new Sequelize( config.db.database , config.db.username , config.db.password , config.db.options ); app.configure( function() { ... // session management app.use( express.cookieParser() ); app.use( express.session({ secret: config.secretKey , cookie: { secure: false, maxAge: 86400000 } , store: new RedisStore({ host: config.redis.host , port: config.redis.port , prefix: config.redis.prefix + process.env.NODE_ENV + '_' , password: config.redis.key }) })); ... });

What it means:

When declaring variables, you use a trailing comma.

Example:

'use strict'; // Get everything ready var config = require( './config' ), express = require( 'express' ), webPort = process.env.NODE_WWW_PORT || config.webPort || 8080, env = process.env.NODE_ENV || config.environmentName || 'development', initializeRoutes = require( './routes' ), modelInjector = require( './src/utils/modelInjector' ), Sequelize = require( 'sequelize' ), Injector = require( './src/utils/injector' ), passport = require( 'passport' ), app = express(); // Setup ORM var sequelize = new Sequelize( config.db.database, config.db.username, config.db.password, config.db.options ); app.configure( function() { ... // session management app.use( express.cookieParser() ); app.use( express.session({ secret: config.secretKey, cookie: { secure: false, maxAge: 86400000 }, store: new RedisStore({ host: config.redis.host, port: config.redis.port prefix: config.redis.prefix + process.env.NODE_ENV + '_', password: config.redis.key }) }) ); ... });

Concatenation

What it means:

When concatenating variables (or expressions), you use a leading operator.

Example:

'use strict'; // Enable cache for css/js/img files app.use( function ( req, res, next ) { var reqURL = req.url; if ( reqURL.indexOf( '/styles/' ) === 0 || reqURL.indexOf( '/scripts/' ) === 0 || reqURL.indexOf( '/images/' ) === 0 || reqURL.indexOf( '/fonts/' ) === 0 || reqURL.indexOf( '/components/' ) === 0 || reqURL.indexOf( '/views/' ) === 0 ) { res.setHeader( 'Cache-Control', 'public, max-age=604800' );// 7 days res.setHeader( 'Expires', new Date( Date.now() + 604800000 ).toUTCString() ); // This is just an example, it doesn't make sense to concatenate this console.log( '##' + ' Sending information' + ' to cache file:', reqURL, '##' ); } next(); });

What it means:

When concatenating variables (or expressions), you use a trailing operator.

Example:

'use strict'; // Enable cache for css/js/img files app.use( function ( req, res, next ) { var reqURL = req.url; if ( reqURL.indexOf( '/styles/' ) === 0 || reqURL.indexOf( '/scripts/' ) === 0 || reqURL.indexOf( '/images/' ) === 0 || reqURL.indexOf( '/fonts/' ) === 0 || reqURL.indexOf( '/components/' ) === 0 || reqURL.indexOf( '/views/' ) === 0 ) { res.setHeader( 'Cache-Control', 'public, max-age=604800' );// 7 days res.setHeader( 'Expires', new Date( Date.now() + 604800000 ).toUTCString() ); // This is just an example, it doesn't make sense to concatenate this console.log( '##' + ' Sending information' + ' to cache file:', reqURL, '##' ); } next(); });

Quotes

This is just a style preference.

This is just a style preference.

Semicolons

This is mostly a style preference.

This is mostly a style preference. Beware of special cases.

Variable Declaration

What it means:

When declaring variables, declare once for each scope.

Example:

'use strict'; // Get everything ready var config = require( './config' ), express = require( 'express' ), webPort = process.env.NODE_WWW_PORT || config.webPort || 8080, env = process.env.NODE_ENV || config.environmentName || 'development', initializeRoutes = require( './routes' ), modelInjector = require( './src/utils/modelInjector' ); function setupORM() { var Sequelize = require( 'sequelize' ), Injector = require( './src/utils/injector' ), passport = require( 'passport' ), app = express(); ... }

What it means:

When declaring variables, declare as needed for each scope.

Beware of variable hoisting.

Example:

'use strict'; // Get everything ready var config = require( './config' ); var express = require( 'express' ); var webPort = process.env.NODE_WWW_PORT || config.webPort || 8080; var env = process.env.NODE_ENV || config.environmentName || 'development'; var initializeRoutes = require( './routes' ); var modelInjector = require( './src/utils/modelInjector' ); function setupORM() { var Sequelize = require( 'sequelize' ), var Injector = require( './src/utils/injector' ), var passport = require( 'passport' ), var app = express(); \n ... }

Require Brackets

What it means:

When doing one-line instructions with if's, for example, always require brackets.

Example:

if ( returnEarly ) { return true; }

What it means:

When doing one-line instructions with if's, for example, don't require brackets.

Example:

if ( returnEarly ) return true;

Preview your JavaScript code guidelines( Will open in a new window )

Why jsCode?

JavaScript is awesome, and while JSLint and JSHint help build better code, there is no real standard for the "details".

We've created this page because we were tired of not having a "common standard" to share coding guidelines with coworkers and other programmers.

The need for customization arose because of the fact people code in a lot of different ways in JavaScript, and it's ok to have preferences, we just all need to agree on them.

How do I use jsCode?

  1. Create a package
  2. Choose the coding standards you agree with
  3. Share it with your coworkers
  4. ???
  5. Profit