From b987a9945cf11c0b6ff05614d77529dea2cd6262 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Thu, 27 Feb 2014 15:19:07 +0200 Subject: [PATCH 01/15] Updated styleguide to better match our customs --- README.md | 69 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index b7d4043297..0ff38a8975 100644 --- a/README.md +++ b/README.md @@ -635,6 +635,7 @@ ## Comments - Use `/** ... */` for multiline comments. Include a description, specify types and values for all parameters and return values. + - Use [JSDoc](http://usejsdoc.org) ```javascript // bad @@ -655,8 +656,8 @@ * make() returns a new element * based on the passed in tag name * - * @param tag - * @return element + * @param {String} tag + * @return {Element} element */ function make(tag) { @@ -696,21 +697,7 @@ } ``` - - Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME -- need to figure this out` or `TODO -- need to implement`. - - - Use `// FIXME:` to annotate problems - - ```javascript - function Calculator() { - - // FIXME: shouldn't use a global here - total = 0; - - return this; - } - ``` - - - Use `// TODO:` to annotate solutions to problems + - Use `@todo` to annotate todos ```javascript function Calculator() { @@ -727,7 +714,7 @@ ## Whitespace - - Use soft tabs set to 2 spaces + - Use soft tabs set to 4 spaces ```javascript // bad @@ -742,7 +729,7 @@ // good function() { - ∙∙var name; + ∙∙∙∙var name; } ``` @@ -771,6 +758,20 @@ breed: 'Bernese Mountain Dog' }); ``` + + - Place 1 space after keywords (such as `if`, `for` and `function`). + + ```javascript + // bad + var foo = function() { + alert('hello'); + }; + + // good + var foo = function () { + alert('hello'); + }; + ``` - Set off operators with spaces. @@ -1066,7 +1067,7 @@ this._firstName = 'Panda'; ``` - - When saving a reference to `this` use `_this`. + - When saving a reference to `this` use `me`. ```javascript // bad @@ -1079,26 +1080,44 @@ // bad function() { - var that = this; + var _this = this; return function() { - console.log(that); + console.log(_this); }; } // good function() { - var _this = this; + var me = this; return function() { - console.log(_this); + console.log(me); }; } ``` + - When implementing the JavaScript module pattern use `that` for referencing + the "public" interface. + + ```javascript + + var mymodule = (function mymodule() { + var that = {}, + privateCounter = 0; + + that.increment = function increment() { + privateCounter += 1; + return privateCounter; + }; + + return that; + })(); + ``` + - Name your functions. This is helpful for stack traces. ```javascript // bad - var log = function(msg) { + var log = function (msg) { console.log(msg); }; From 6d405d309434db41ad8123fae106154db2703249 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Tue, 1 Apr 2014 19:43:13 +0300 Subject: [PATCH 02/15] if-else conventions --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 82b7ff32cf..34cb2b5a34 100644 --- a/README.md +++ b/README.md @@ -624,6 +624,42 @@ } ``` + - Put `else` and `catch` on the same line with closing brace. + + ```javascript + // bad + if (test) { + return true; + } + else { + return false; + } + + // good + if (test) { + return 1; + } else if (anotherTest) { + return 0; + } else { + return -1; + } + + // bad + try { + dragonsBeHere(); + } + catch (e) { + log.error('very bad: ' + e); + } + + // good + try { + dragonsBeHere(); + } catch (e) { + log.error('very bad: ' + e); + } + ``` + **[⬆ back to top](#table-of-contents)** @@ -753,15 +789,15 @@ breed: 'Bernese Mountain Dog' }); ``` - + - Place 1 space after keywords (such as `if`, `for` and `function`). - + ```javascript // bad var foo = function() { alert('hello'); }; - + // good var foo = function () { alert('hello'); @@ -1094,16 +1130,16 @@ the "public" interface. ```javascript - + var mymodule = (function mymodule() { var that = {}, privateCounter = 0; - + that.increment = function increment() { privateCounter += 1; return privateCounter; }; - + return that; })(); ``` From 972804d4aefa329becefde81cb11dfb245b2cb94 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Tue, 1 Apr 2014 20:28:29 +0300 Subject: [PATCH 03/15] more conventions for variable declaration --- README.md | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 86 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 82b7ff32cf..43c88a6f3c 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,86 @@ } ``` + - Only use single line for each variable. + + ```javascript + // bad + function () { + var count = 0, + options = { + name: 'Luke', + race: 'Jedi' + }, + i; + + // ... + } + + // good + function () { + var count = 0, + options, + i; + + options = { + name: 'Luke', + race: 'Jedi + }; + + // ... + } + + - For readability, only use single comment line for a variable if + necessary. Prefer documenting variable in the function documentation. + + ```javascript + // bad + function () { + var count, + + /* Hash that contain character options. + * + * @typedef options + * @property {String} name - Name of the character. + * @property {String} race - Race of the character. + */ + options, + + // index for the for loop. + i; + + // ... + } + + // better + function () { + var count, + // character's options hash + options, + i; + } + + // good + function () { + var count, + characterOptions, + i; + + // ... + } + + // good + /** + * ... + * + * Internally, character's options are stored in the `options` hash. + */ + function () { + var count, + options, + i; + } + **[⬆ back to top](#table-of-contents)** @@ -753,15 +833,15 @@ breed: 'Bernese Mountain Dog' }); ``` - + - Place 1 space after keywords (such as `if`, `for` and `function`). - + ```javascript // bad var foo = function() { alert('hello'); }; - + // good var foo = function () { alert('hello'); @@ -1094,16 +1174,16 @@ the "public" interface. ```javascript - + var mymodule = (function mymodule() { var that = {}, privateCounter = 0; - + that.increment = function increment() { privateCounter += 1; return privateCounter; }; - + return that; })(); ``` From d4b343c1b7e4b41d2c665c08f595f1061ea0f319 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Tue, 1 Apr 2014 20:30:29 +0300 Subject: [PATCH 04/15] fixed markdown syntax --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 43c88a6f3c..f0c7fad561 100644 --- a/README.md +++ b/README.md @@ -485,6 +485,7 @@ // ... } + ``` - For readability, only use single comment line for a variable if necessary. Prefer documenting variable in the function documentation. @@ -536,6 +537,7 @@ options, i; } + ``` **[⬆ back to top](#table-of-contents)** From 5ed38e8ba8e3870dc6c627ae235379b76b731354 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Fri, 13 Jun 2014 09:35:41 +0300 Subject: [PATCH 05/15] added missing comma --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 239befb6f3..37d4fabac8 100644 --- a/README.md +++ b/README.md @@ -480,7 +480,7 @@ options = { name: 'Luke', - race: 'Jedi + race: 'Jedi' }; // ... From 95b11220e448dd368ec137f06e6d253f6a3cd92b Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Fri, 13 Jun 2014 09:41:44 +0300 Subject: [PATCH 06/15] added space after function keyword --- README.md | 72 +++++++++++++++++++++++++++---------------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 066146a72b..310984031e 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ ```javascript // anonymous function expression - var anonymous = function() { + var anonymous = function () { return true; }; @@ -273,7 +273,7 @@ }; // immediately-invoked function expression (IIFE) - (function() { + (function () { console.log('Welcome to the Internet. Please follow me.'); })(); ``` @@ -403,7 +403,7 @@ ```javascript // bad - function() { + function () { test(); console.log('doing stuff..'); @@ -419,7 +419,7 @@ } // good - function() { + function () { var name = getName(); test(); @@ -435,7 +435,7 @@ } // bad - function() { + function () { var name = getName(); if (!arguments.length) { @@ -446,7 +446,7 @@ } // good - function() { + function () { if (!arguments.length) { return false; } @@ -580,7 +580,7 @@ anonymous(); // => TypeError anonymous is not a function - var anonymous = function() { + var anonymous = function () { console.log('anonymous function expression'); }; } @@ -698,10 +698,10 @@ } // bad - function() { return false; } + function () { return false; } // good - function() { + function () { return false; } ``` @@ -831,17 +831,17 @@ ```javascript // bad - function() { + function () { ∙∙∙∙var name; } // bad - function() { + function () { ∙var name; } // good - function() { + function () { ∙∙∙∙var name; } ``` @@ -876,7 +876,7 @@ ```javascript // bad - var foo = function() { + var foo = function () { alert('hello'); }; @@ -900,14 +900,14 @@ ```javascript // bad - (function(global) { + (function (global) { // ...stuff... })(this); ``` ```javascript // bad - (function(global) { + (function (global) { // ...stuff... })(this);↵ ↵ @@ -915,7 +915,7 @@ ```javascript // good - (function(global) { + (function (global) { // ...stuff... })(this);↵ ``` @@ -1022,19 +1022,19 @@ ```javascript // bad - (function() { + (function () { var name = 'Skywalker' return name })() // good - (function() { + (function () { var name = 'Skywalker'; return name; })(); // good - ;(function() { + ;(function () { var name = 'Skywalker'; return name; })(); @@ -1155,7 +1155,7 @@ // good var thisIsMyObject = {}; - function thisIsMyFunction() {} + function thisIsMyfunction () {} var user = new User({ name: 'Bob Parr' }); @@ -1198,25 +1198,25 @@ ```javascript // bad - function() { + function () { var self = this; - return function() { + return function () { console.log(self); }; } // bad - function() { + function () { var _this = this; - return function() { + return function () { console.log(_this); }; } // good - function() { + function () { var me = this; - return function() { + return function () { console.log(me); }; } @@ -1301,11 +1301,11 @@ this.set('lightsaber', lightsaber); } - Jedi.prototype.set = function(key, val) { + Jedi.prototype.set = function (key, val) { this[key] = val; }; - Jedi.prototype.get = function(key) { + Jedi.prototype.get = function (key) { return this[key]; }; ``` @@ -1347,12 +1347,12 @@ ```javascript // bad - Jedi.prototype.jump = function() { + Jedi.prototype.jump = function () { this.jumping = true; return true; }; - Jedi.prototype.setHeight = function(height) { + Jedi.prototype.setHeight = function (height) { this.height = height; }; @@ -1361,12 +1361,12 @@ luke.setHeight(20) // => undefined // good - Jedi.prototype.jump = function() { + Jedi.prototype.jump = function () { this.jumping = true; return this; }; - Jedi.prototype.setHeight = function(height) { + Jedi.prototype.setHeight = function (height) { this.height = height; return this; }; @@ -1408,7 +1408,7 @@ ... - $(this).on('listingUpdated', function(e, listingId) { + $(this).on('listingUpdated', function (e, listingId) { // do something with listingId }); ``` @@ -1421,7 +1421,7 @@ ... - $(this).on('listingUpdated', function(e, data) { + $(this).on('listingUpdated', function (e, data) { // do something with data.listingId }); ``` @@ -1439,7 +1439,7 @@ ```javascript // fancyInput/fancyInput.js - !function(global) { + !function (global) { 'use strict'; var previousFancyInput = global.FancyInput; @@ -1534,7 +1534,7 @@ - **Yup.** ```javascript - function() { + function () { return true; } ``` From c7edda7af6d18ada10490677d460fea2b85e2490 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Fri, 13 Jun 2014 09:44:43 +0300 Subject: [PATCH 07/15] whitespace adjustments --- README.md | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 310984031e..a87ca51160 100644 --- a/README.md +++ b/README.md @@ -832,7 +832,7 @@ ```javascript // bad function () { - ∙∙∙∙var name; + var name; } // bad @@ -851,24 +851,24 @@ ```javascript // bad function test(){ - console.log('test'); + console.log('test'); } // good function test() { - console.log('test'); + console.log('test'); } // bad dog.set('attr',{ - age: '1 year', - breed: 'Bernese Mountain Dog' + age: '1 year', + breed: 'Bernese Mountain Dog' }); // good dog.set('attr', { - age: '1 year', - breed: 'Bernese Mountain Dog' + age: '1 year', + breed: 'Bernese Mountain Dog' }); ``` @@ -901,14 +901,14 @@ ```javascript // bad (function (global) { - // ...stuff... + // ...stuff... })(this); ``` ```javascript // bad (function (global) { - // ...stuff... + // ...stuff... })(this);↵ ↵ ``` @@ -916,7 +916,7 @@ ```javascript // good (function (global) { - // ...stuff... + // ...stuff... })(this);↵ ``` @@ -928,11 +928,11 @@ // good $('#items') - .find('.selected') - .highlight() - .end() - .find('.open') - .updateCount(); + .find('.selected') + .highlight() + .end() + .find('.open') + .updateCount(); // bad var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true) @@ -942,13 +942,13 @@ // good var leds = stage.selectAll('.led') - .data(data) - .enter().append('svg:svg') - .class('led', true) - .attr('width', (radius + margin) * 2) - .append('svg:g') - .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') - .call(tron.led); + .data(data) + .enter().append('svg:svg') + .class('led', true) + .attr('width', (radius + margin) * 2) + .append('svg:g') + .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') + .call(tron.led); ``` **[⬆ back to top](#table-of-contents)** From 566236e1bf32b8fa4a5487e4852f94a7c1d560bb Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Thu, 26 Jun 2014 18:37:15 +0300 Subject: [PATCH 08/15] added more conventions --- README.md | 129 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 93 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index a87ca51160..69a3e07073 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,12 @@ 1. [Whitespace](#whitespace) 1. [Commas](#commas) 1. [Semicolons](#semicolons) + 1. [File Headers](#file-headers) 1. [Type Casting & Coercion](#type-casting--coercion) 1. [Naming Conventions](#naming-conventions) 1. [Accessors](#accessors) 1. [Constructors](#constructors) + 1. [Functional Style](#functional-style) 1. [Events](#events) 1. [Modules](#modules) 1. [jQuery](#jquery) @@ -747,7 +749,12 @@ ## Comments - - Use `/** ... */` for multiline comments. Include a description, specify types and values for all parameters and return values. + - Use `/** ... */` for multiline comments. Include a description, specify + types and values for necessary parameters and return values. + - First sentence of the function docstring should fit on one line and + should prescribe the function's effect as a command ("Do this", + "Return that"), not as a description; e.g. don't write "Returns the + pathname ..." - Use [JSDoc](http://usejsdoc.org) ```javascript @@ -766,11 +773,13 @@ // good /** - * make() returns a new element - * based on the passed in tag name + * Return a new element. * - * @param {String} tag - * @return {Element} element + * This is a longer description of the function and will + * give all the necessary details. + * + * @param {String} tag - descriptive tag + * @returns {Element} element */ function make(tag) { @@ -815,7 +824,7 @@ ```javascript function Calculator() { - // TODO: total should be configurable by an options param + // @todo total should be configurable by an options param this.total = 0; return this; @@ -876,7 +885,7 @@ ```javascript // bad - var foo = function () { + var foo = function() { alert('hello'); }; @@ -985,9 +994,17 @@ }; ``` - - Additional trailing comma: **Nope.** This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 ([source](http://es5.github.io/#D)): + - Additional trailing comma: **Nope.** This can cause problems with IE6/7 and + IE9 if it's in quirksmode. Also, in some implementations of ES3 would add + length to an array if it had an additional trailing comma. This was + clarified in ES5 ([source](http://es5.github.io/#D)): + + > Edition 5 clarifies the fact that a trailing comma at the end of an + ArrayInitialiser does not add to the length of the array. This is not a + semantic change from Edition 3 but some implementations may have previously + misinterpreted this. - > Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this. + It is fine to use the extra comma in node.js environment. ```javascript // bad @@ -1043,6 +1060,25 @@ **[⬆ back to top](#table-of-contents)** +## File Headers + +All JavaScript files should have the following file header and footer: + + ```javascript + // -*- coding: utf-8 -*- + // filename.js + // created: 2014-05-22 08:10:10 + // + + + + // + // filename.js ends here + + +**[⬆ back to top](#table-of-contents)** + + ## Type Casting & Coercion - Perform type coercion at the beginning of the statement. @@ -1183,7 +1219,9 @@ }); ``` - - Use a leading underscore `_` when naming private properties + - Use a leading underscore `_` when naming private properties (note that + this is not necessary when using the module pattern or when protecting + ES5 style variables with `Object.create()`) ```javascript // bad @@ -1398,6 +1436,34 @@ **[⬆ back to top](#table-of-contents)** +## Functional Style + + - Avoid generic for-loops (i.e. `for (i = 0; i < array.length; i += 1)) + because + - They make code difficult to read + - They may have all kinds of side effects + - Prefer using functional programming constructs such as + - `map`: to convert an array to another array + - `reduce`: to reduce an array of items into a single value + - `filter`: to filter out unwanted elements + - Familiarize yourself with all different functions available in the + [lodash](http://lodash.com/docs) library. When it comes to dealing with + collections, most of the time it already has what you would otherwise + have to implement yourself. + - Using these functions makes it easy for the reader to immediately + understand what the code is doing and they don't (must not) have + side effects. + - `forEach` is the only exception where we allow the code inside the loop to + have side effects since it has been used for drop-in replacement for more + traditional `for (i = 0; i < array.length; i += 1)` construct. + - Sometimes though, for performance reasons for large collections, you may + want to consider replacing subsequent functional constructs with single + for-loop where you do many things at once. This should be vare rare however. + + +**[⬆ back to top](#table-of-contents)** + + ## Events - When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of: @@ -1431,31 +1497,10 @@ ## Modules - - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) - - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export. - - Add a method called `noConflict()` that sets the exported module to the previous version and returns this one. + - In Node.js files should be named with camelCase. + - In Ember projects files should be named with hyphens (e.g. `route-header.js`). - Always declare `'use strict';` at the top of the module. - ```javascript - // fancyInput/fancyInput.js - - !function (global) { - 'use strict'; - - var previousFancyInput = global.FancyInput; - - function FancyInput(options) { - this.options = options || {}; - } - - FancyInput.noConflict = function noConflict() { - global.FancyInput = previousFancyInput; - return FancyInput; - }; - - global.FancyInput = FancyInput; - }(this); - ``` **[⬆ back to top](#table-of-contents)** @@ -1531,14 +1576,26 @@ ## Testing - - **Yup.** +### Testing private functions in Node.js + + - Gather all private functions in private variable called `internals` + - Expose the `internals` variable when running tests ```javascript - function () { - return true; + var internals = {}; + + internals.myPrivateFunction = function () { + // do private stuff + }; + + // in the end of the module expose internals for tests + if (process.env.NODE_ENV === 'test') { + exports.internals = internals; } ``` + + **[⬆ back to top](#table-of-contents)** From 5f9d0ebbd3a6cd4348cd278408a96f719d5f58bb Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Thu, 26 Jun 2014 18:41:46 +0300 Subject: [PATCH 09/15] fixed typos --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 69a3e07073..8437163b3f 100644 --- a/README.md +++ b/README.md @@ -1438,7 +1438,7 @@ All JavaScript files should have the following file header and footer: ## Functional Style - - Avoid generic for-loops (i.e. `for (i = 0; i < array.length; i += 1)) + - Avoid generic for-loops (i.e. `for (i = 0; i < array.length; i += 1)`) because - They make code difficult to read - They may have all kinds of side effects @@ -1450,15 +1450,15 @@ All JavaScript files should have the following file header and footer: [lodash](http://lodash.com/docs) library. When it comes to dealing with collections, most of the time it already has what you would otherwise have to implement yourself. - - Using these functions makes it easy for the reader to immediately - understand what the code is doing and they don't (must not) have - side effects. + - Using these functions makes it easy for the reader to quickly see + what the code is supposed to be doing and the reader can trust that the + code inside the loop doesn't (must not) have any side effects. - `forEach` is the only exception where we allow the code inside the loop to have side effects since it has been used for drop-in replacement for more traditional `for (i = 0; i < array.length; i += 1)` construct. - Sometimes though, for performance reasons for large collections, you may want to consider replacing subsequent functional constructs with single - for-loop where you do many things at once. This should be vare rare however. + for-loop where you do many things at once. This should be vary rare however. **[⬆ back to top](#table-of-contents)** From bb2600d4e2fb915a0956b5a47788b479ccd23d8e Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Thu, 26 Jun 2014 18:43:02 +0300 Subject: [PATCH 10/15] fixed markdown syntax --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8437163b3f..5133acac13 100644 --- a/README.md +++ b/README.md @@ -1064,16 +1064,16 @@ All JavaScript files should have the following file header and footer: - ```javascript - // -*- coding: utf-8 -*- - // filename.js - // created: 2014-05-22 08:10:10 - // + ```javascript + // -*- coding: utf-8 -*- + // filename.js + // created: 2014-05-22 08:10:10 + // - // - // filename.js ends here + // + // filename.js ends here **[⬆ back to top](#table-of-contents)** From 8a8df523f8fcc181eda25e4d82c8396535528220 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Thu, 26 Jun 2014 18:43:41 +0300 Subject: [PATCH 11/15] fixed markdown syntax --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5133acac13..e932a6e4d2 100644 --- a/README.md +++ b/README.md @@ -1074,6 +1074,7 @@ All JavaScript files should have the following file header and footer: // // filename.js ends here + ``` **[⬆ back to top](#table-of-contents)** From 9c3aee8f956502908beb1b35c31b1ddde5a304f8 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Thu, 26 Jun 2014 19:08:10 +0300 Subject: [PATCH 12/15] added note about utf-8 encoding --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e932a6e4d2..aeddfcd330 100644 --- a/README.md +++ b/README.md @@ -1500,6 +1500,7 @@ All JavaScript files should have the following file header and footer: - In Node.js files should be named with camelCase. - In Ember projects files should be named with hyphens (e.g. `route-header.js`). + - All files should use `utf-8` encoding. - Always declare `'use strict';` at the top of the module. From 4677b1389cc3a30cc7ec83fed1e3e50a506e011d Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Wed, 27 Aug 2014 22:02:29 +0300 Subject: [PATCH 13/15] added stuff about comments --- README.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index aeddfcd330..e7053abc84 100644 --- a/README.md +++ b/README.md @@ -749,13 +749,37 @@ ## Comments - - Use `/** ... */` for multiline comments. Include a description, specify + - Use following format for function/class comments: + + ```javascript + /** + * + */ + ``` + + - Other (random) multiline comments should take either of + the following two forms: + + ```javascript + /* + * + */ + + // + // + // + ``` + + - In function comments, include description, specify types and values for necessary parameters and return values. - First sentence of the function docstring should fit on one line and should prescribe the function's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ..." - Use [JSDoc](http://usejsdoc.org) + - You don't always have to document every parameter and return value if + they are obvious. + - Use `@typedef` to specify complex structures. ```javascript // bad From 620138112a2284314b32f8f138ab07bffafbfd1f Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Wed, 4 Feb 2015 21:47:30 +0200 Subject: [PATCH 14/15] revised some parts of the styleguide --- README.md | 86 +++++-------------------------------------------------- 1 file changed, 7 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index e7053abc84..8827d7846f 100644 --- a/README.md +++ b/README.md @@ -109,11 +109,6 @@ class: 'alien' }; - // bad - var superman = { - klass: 'alien' - }; - // good var superman = { type: 'alien' @@ -757,19 +752,19 @@ */ ``` - - Other (random) multiline comments should take either of + - Other (random) multiline comments should take either of the following two forms: - + ```javascript /* * */ - + // // // ``` - + - In function comments, include description, specify types and values for necessary parameters and return values. - First sentence of the function docstring should fit on one line and @@ -777,7 +772,7 @@ "Return that"), not as a description; e.g. don't write "Returns the pathname ..." - Use [JSDoc](http://usejsdoc.org) - - You don't always have to document every parameter and return value if + - You don't always have to document every parameter and return value if they are obvious. - Use `@typedef` to specify complex structures. @@ -816,12 +811,6 @@ - Use `//` for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment. ```javascript - // bad - var active = true; // is current tab - - // good - // is current tab - var active = true; // bad function getType() { @@ -1303,20 +1292,6 @@ All JavaScript files should have the following file header and footer: })(); ``` - - Name your functions. This is helpful for stack traces. - - ```javascript - // bad - var log = function (msg) { - console.log(msg); - }; - - // good - var log = function log(msg) { - console.log(msg); - }; - ``` - - **Note:** IE8 and below exhibit some quirks with named function expressions. See [http://kangax.github.io/nfe/](http://kangax.github.io/nfe/) for more info. **[⬆ back to top](#table-of-contents)** @@ -1324,54 +1299,7 @@ All JavaScript files should have the following file header and footer: ## Accessors - - Accessor functions for properties are not required - - If you do make accessor functions use getVal() and setVal('hello') - - ```javascript - // bad - dragon.age(); - - // good - dragon.getAge(); - - // bad - dragon.age(25); - - // good - dragon.setAge(25); - ``` - - - If the property is a boolean, use isVal() or hasVal() - - ```javascript - // bad - if (!dragon.age()) { - return false; - } - - // good - if (!dragon.hasAge()) { - return false; - } - ``` - - - It's okay to create get() and set() functions, but be consistent. - - ```javascript - function Jedi(options) { - options || (options = {}); - var lightsaber = options.lightsaber || 'blue'; - this.set('lightsaber', lightsaber); - } - - Jedi.prototype.set = function (key, val) { - this[key] = val; - }; - - Jedi.prototype.get = function (key) { - return this[key]; - }; - ``` + - Accessor functions (simle getters and setters) for properties are not required **[⬆ back to top](#table-of-contents)** @@ -1406,7 +1334,7 @@ All JavaScript files should have the following file header and footer: }; ``` - - Methods can return `this` to help with method chaining. + - Methods should return `this` to help with method chaining. ```javascript // bad From 6834c45d3d1ce09e4ed51d9785d2d030a917feb4 Mon Sep 17 00:00:00 2001 From: Janne Kuuskeri Date: Wed, 4 Feb 2015 22:18:31 +0200 Subject: [PATCH 15/15] parting words --- README.md | 113 +++++++++++++++++++++++++----------------------------- 1 file changed, 52 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 8827d7846f..90a58d0163 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ 1. [Conditional Expressions & Equality](#conditional-expressions--equality) 1. [Blocks](#blocks) 1. [Comments](#comments) + 1. [Line Length](#line-length) 1. [Whitespace](#whitespace) 1. [Commas](#commas) 1. [Semicolons](#semicolons) @@ -30,10 +31,8 @@ 1. [jQuery](#jquery) 1. [ECMAScript 5 Compatibility](#ecmascript-5-compatibility) 1. [Testing](#testing) - 1. [Performance](#performance) + 1. [Parting Words](#parting-words) 1. [Resources](#resources) - 1. [In the Wild](#in-the-wild) - 1. [Translation](#translation) 1. [The JavaScript Style Guide Guide](#the-javascript-style-guide-guide) 1. [Contributors](#contributors) 1. [License](#license) @@ -847,6 +846,33 @@ **[⬆ back to top](#table-of-contents)** +## Line Length + +All JSHint rules should be set to max 100 char line length. There are some +cases where it is actually better for readability if this rule is broken. A +good example would be a REST API definition on the server side. In those +cases, override the JSHint rule for that code block. For example: + + ```javascript + /*jshint maxlen:200*/ + + ... + { + name: 'releaseServiceWindow', + version: 1, + urls: [ + { path: '/schedule/{sid}/service-window/', name: 'schedule/serviceWindow' }, + { path: '/schedule/{sid}/service-window/{swid}', name: 'schedule/serviceWindow/*'} + ] + }, + ... + + /*jshint maxlen:100*/ + ``` + +**[⬆ back to top](#table-of-contents)** + + ## Whitespace - Use soft tabs set to 4 spaces @@ -1549,20 +1575,23 @@ All JavaScript files should have the following file header and footer: ``` - **[⬆ back to top](#table-of-contents)** -## Performance +## Parting Words - - [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/) - - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2) - - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost) - - [Bang Function](http://jsperf.com/bang-function) - - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13) - - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text) - - [Long String Concatenation](http://jsperf.com/ya-string-concat) - - Loading... +Remeber that: + +*"Code is read many more times than it is written"* + +So, it's all about readability. If any of the conventions laid out on this page +contradicts with readability in a given scenario, feel free to break the +convention to make way for better readability. + +Bear in mind though that linting errors are considered real errors and all +projects must pass with zero linting errors. Therefore, if you have to break +one of the JSHint rules, override the rule for that file or for that code +block instead of changing the global project rules. **[⬆ back to top](#table-of-contents)** @@ -1574,6 +1603,16 @@ All JavaScript files should have the following file header and footer: - [Annotated ECMAScript 5.1](http://es5.github.com/) +**Performance** + + - [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/) + - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2) + - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost) + - [Bang Function](http://jsperf.com/bang-function) + - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13) + - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text) + - [Long String Concatenation](http://jsperf.com/ya-string-concat) + **Other Styleguides** - [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml) @@ -1625,54 +1664,6 @@ All JavaScript files should have the following file header and footer: **[⬆ back to top](#table-of-contents)** -## In the Wild - - This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list. - - - **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript) - - **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript) - - **American Insitutes for Research**: [AIRAST/javascript](https://github.com/AIRAST/javascript) - - **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide) - - **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript) - - **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript) - - **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript) - - **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript) - - **GeneralElectric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript) - - **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style) - - **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript) - - **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript) - - **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript) - - **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript) - - **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript) - - **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript) - - **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript) - - **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript) - - **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript) - - **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript) - - **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide) - - **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide) - - **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript) - - **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide) - - **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide) - - **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript) - - **Userify**: [userify/javascript](https://github.com/userify/javascript) - - **Zillow**: [zillow/javascript](https://github.com/zillow/javascript) - - **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript) - -## Translation - - This style guide is also available in other languages: - - - :de: **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide) - - :jp: **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide) - - :br: **Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide) - - :cn: **Chinese**: [adamlu/javascript-style-guide](https://github.com/adamlu/javascript-style-guide) - - :es: **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide) - - :kr: **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide) - - :fr: **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide) - - :ru: **Russian**: [uprock/javascript](https://github.com/uprock/javascript) - - :bg: **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript) - ## The JavaScript Style Guide Guide - [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)