Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Principles of Writing Consistent, Idiomatic JavaScript

NotificationsYou must be signed in to change notification settings

rwaldron/idiomatic.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This is a living document and new ideas for improving the code around us are always welcome. Contribute: fork, clone, branch, commit, push, pull request.

All code in any code-base should look like a single person typed it, no matter how many people contributed.

The following list outlines the practices that I use in all code that I am the original author of; contributions to projects that I have created should follow these guidelines.

I do not intend to impose my style preferences on other people's code or projects; if an existing common style exists, it should be respected.

"Arguments over style are pointless. There should be a style guide, and you should follow it"

RebeccaMurphey

 

"Part of being a good steward to a successful project is realizing that writing code for yourself is a Bad Idea™. If thousands of people are using your code, then write your code for maximum clarity, not your personal preference of how to get clever within the spec."

IdanGazit

Translations

Important, Non-Idiomatic Stuff:

Code Quality Tools, Resources & References

Get Smart

The following should be considered 1) incomplete, and 2)REQUIRED READING. I don't always agree with the style written by the authors below, but one thing is certain: They are consistent. Furthermore, these are authorities on the language.

Build & Deployment Process

Projects should always attempt to include some generic means by which source can be linted, tested and compressed in preparation for production use. For this task,grunt by Ben Alman is second to none and has officially replaced the "kits/" directory of this repo.

Test Facility

Projectsmust include some form of unit, reference, implementation or functional testing. Use case demos DO NOT QUALIFY as "tests". The following is a list of test frameworks, none of which are endorsed more than the other.

Table of Contents


Preface

The following sections outline areasonable style guide for modern JavaScript development and are not meant to be prescriptive. The most important take-away is thelaw of code style consistency. Whatever you choose as the style for your project should be considered law. Link to this document as a statement of your project's commitment to code style consistency, readability and maintainability.

Idiomatic Style Manifesto

  1. Whitespace
  • Never mix spaces and tabs.
  • When beginning a project, before you write any code, choose between soft indents (spaces) or real tabs, consider thislaw.
    • For readability, I always recommend setting your editor's indent size to two characters — this means two spaces or two spaces representing a real tab.
  • If your editor supports it, always work with the "show invisibles" setting turned on. The benefits of this practice are:
    • Enforced consistency
    • Eliminating end of line whitespace
    • Eliminating blank line whitespace
    • Commits and diffs that are easier to read
  • UseEditorconfig when possible. It supports most IDEs and handles most whitespace settings.
  1. Beautiful Syntax

    A. Parens, Braces, Linebreaks

    // if/else/for/while/try always have spaces, braces and span multiple lines// this encourages readability// 2.A.1.1// Examples of really cramped syntaxif(condition)doSomething();while(condition)iterating++;for(vari=0;i<100;i++)someIterativeFn();// 2.A.1.1// Use whitespace to promote readabilityif(condition){// statements}while(condition){// statements}for(vari=0;i<100;i++){// statements}// Even better:vari,length=100;for(i=0;i<length;i++){// statements}// Or...vari=0,length=100;for(;i<length;i++){// statements}varprop;for(propinobject){// statements}if(true){// statements}else{// statements}

    B. Assignments, Declarations, Functions ( Named, Expression, Constructor )

    // 2.B.1.1// Variablesvarfoo="bar",num=1,undef;// Literal notations:vararray=[],object={};// 2.B.1.2// Using only one `var` per scope (function) or one `var` for each variable,// promotes readability and keeps your declaration list free of clutter.// Using one `var` per variable you can take more control of your versions// and makes it easier to reorder the lines.// One `var` per scope makes it easier to detect undeclared variables// that may become implied globals.// Choose better for your project and never mix them.// Badvarfoo="",bar="";varqux;// Goodvarfoo="";varbar="";varqux;// or..varfoo="",bar="",qux;// or..var// Comment on thesefoo="",bar="",quux;// 2.B.1.3// var statements should always be in the beginning of their respective scope (function).// Badfunctionfoo(){// some statements herevarbar="",qux;}// Goodfunctionfoo(){varbar="",qux;// all statements after the variables declarations.}// 2.B.1.4// const and let, from ECMAScript 6, should likewise be at the top of their scope (block).// Badfunctionfoo(){letfoo,bar;if(condition){bar="";// statements}}// Goodfunctionfoo(){letfoo;if(condition){letbar="";// statements}}
    // 2.B.2.1// Named Function Declarationfunctionfoo(arg1,argN){}// Usagefoo(arg1,argN);// 2.B.2.2// Named Function Declarationfunctionsquare(number){returnnumber*number;}// Usagesquare(10);// Really contrived continuation passing stylefunctionsquare(number,callback){callback(number*number);}square(10,function(square){// callback statements});// 2.B.2.3// Function Expressionvarsquare=function(number){// Return something valuable and relevantreturnnumber*number;};// Function Expression with Identifier// This preferred form has the added value of being// able to call itself and have an identity in stack traces:varfactorial=functionfactorial(number){if(number<2){return1;}returnnumber*factorial(number-1);};// 2.B.2.4// Constructor DeclarationfunctionFooBar(options){this.options=options;}// UsagevarfooBar=newFooBar({a:"alpha"});fooBar.options;// { a: "alpha" }

    C. Exceptions, Slight Deviations

    // 2.C.1.1// Functions with callbacksfoo(function(){// Note there is no extra space between the first paren// of the executing function call and the word "function"});// Function accepting an array, no spacefoo(["alpha","beta"]);// 2.C.1.2// Function accepting an object, no spacefoo({a:"alpha",b:"beta"});// Single argument string literal, no spacefoo("bar");// Expression parens, no spaceif(!("foo"inobj)){obj=(obj.bar||defaults).baz;}

    D. Consistency Always Wins

    In sections 2.A-2.C, the whitespace rules are set forth as a recommendation with a simpler, higher purpose: consistency.It's important to note that formatting preferences, such as "inner whitespace" should be considered optional, but only one style should exist across the entire source of your project.

    // 2.D.1.1if(condition){// statements}while(condition){// statements}for(vari=0;i<100;i++){// statements}if(true){// statements}else{// statements}

    E. Quotes

    Whether you prefer single or double shouldn't matter, there is no difference in how JavaScript parses them. WhatABSOLUTELY MUST be enforced is consistency.Never mix quotes in the same project. Pick one style and stick with it.

    F. End of Lines and Empty Lines

    Whitespace can ruin diffs and make changesets impossible to read. Consider incorporating a pre-commit hook that removes end-of-line whitespace and blanks spaces on empty lines automatically.

  2. Type Checking (Courtesy jQuery Core Style Guidelines)

    A. Actual Types

    String:

     typeof variable === "string"

    Number:

     typeof variable === "number"

    Boolean:

     typeof variable === "boolean"

    Object:

     typeof variable === "object"

    Array:

     Array.isArray( arrayLikeObject ) (wherever possible)

    Node:

     elem.nodeType === 1

    null:

     variable === null

    null or undefined:

     variable == null

    undefined:

    Global Variables:

     typeof variable === "undefined"

    Local Variables:

     variable === undefined

    Properties:

     object.prop === undefined object.hasOwnProperty( prop ) "prop" in object

    B. Coerced Types

    Consider the implications of the following...

    Given this HTML:

    <inputtype="text"id="foo-input"value="1">
    // 3.B.1.1// `foo` has been declared with the value `0` and its type is `number`varfoo=0;// typeof foo;// "number"...// Somewhere later in your code, you need to update `foo`// with a new value derived from an input elementfoo=document.getElementById("foo-input").value;// If you were to test `typeof foo` now, the result would be `string`// This means that if you had logic that tested `foo` like:if(foo===1){importantTask();}// `importantTask()` would never be evaluated, even though `foo` has a value of "1"// 3.B.1.2// You can preempt issues by using smart coercion with unary + or - operators:foo=+document.getElementById("foo-input").value;//    ^ unary + operator will convert its right side operand to a number// typeof foo;// "number"if(foo===1){importantTask();}// `importantTask()` will be called

    Here are some common cases along with coercions:

    // 3.B.2.1varnumber=1,string="1",bool=false;number;// 1number+"";// "1"string;// "1"+string;// 1+string++;// 1string;// 2bool;// false+bool;// 0bool+"";// "false"
    // 3.B.2.2varnumber=1,string="1",bool=true;string===number;// falsestring===number+"";// true+string===number;// truebool===number;// false+bool===number;// truebool===string;// falsebool===!!string;// true
    // 3.B.2.3vararray=["a","b","c"];!!~array.indexOf("a");// true!!~array.indexOf("b");// true!!~array.indexOf("c");// true!!~array.indexOf("d");// false// Note that the above should be considered "unnecessarily clever"// Prefer the obvious approach of comparing the returned value of// indexOf, like:if(array.indexOf("a")>=0){// ...}
    // 3.B.2.4varnum=2.5;parseInt(num,10);// is the same as...~~num;num>>0;num>>>0;// All result in 2// Keep in mind however, that negative numbers will be treated differently...varneg=-2.5;parseInt(neg,10);// is the same as...~~neg;neg>>0;// All result in -2// However...neg>>>0;// Will result in 4294967294
  3. Conditional Evaluation

    // 4.1.1// When only evaluating that an array has length,// instead of this:if(array.length>0) ...// ...evaluate truthiness, like this:if(array.length) ...// 4.1.2// When only evaluating that an array is empty,// instead of this:if(array.length===0) ...// ...evaluate truthiness, like this:if(!array.length) ...// 4.1.3// When only evaluating that a string is not empty,// instead of this:if(string!=="") ...// ...evaluate truthiness, like this:if(string) ...// 4.1.4// When only evaluating that a string _is_ empty,// instead of this:if(string==="") ...// ...evaluate falsy-ness, like this:if(!string) ...// 4.1.5// When only evaluating that a reference is true,// instead of this:if(foo===true) ...// ...evaluate like you mean it, take advantage of built in capabilities:if(foo) ...// 4.1.6// When evaluating that a reference is false,// instead of this:if(foo===false) ...// ...use negation to coerce a true evaluationif(!foo) ...// ...Be careful, this will also match: 0, "", null, undefined, NaN// If you _MUST_ test for a boolean false, then useif(foo===false) ...// 4.1.7// When only evaluating a ref that might be null or undefined, but NOT false, "" or 0,// instead of this:if(foo===null||foo===undefined) ...// ...take advantage of == type coercion, like this:if(foo==null) ...// Remember, using == will match a `null` to BOTH `null` and `undefined`// but not `false`, "" or 0null==undefined

    ALWAYS evaluate for the best, most accurate result - the above is a guideline, not a dogma.

    // 4.2.1// Type coercion and evaluation notes// Prefer `===` over `==` (unless the case requires loose type evaluation)// === does not coerce type, which means that:"1"===1;// false// == does coerce type, which means that:"1"==1;// true// 4.2.2// Booleans, Truthies & Falsies// Booleans:true,false// Truthy:"foo",1// Falsy:"",0,null,undefined,NaN,void0
  4. Practical Style

    // 5.1.1// A Practical Module(function(global){varModule=(function(){vardata="secret";return{// This is some boolean propertybool:true,// Some string valuestring:"a string",// An array propertyarray:[1,2,3,4],// An object propertyobject:{lang:"en-Us"},getData:function(){// get the current value of `data`returndata;},setData:function(value){// set the value of `data` and return itreturn(data=value);}};})();// Other things might happen here// expose our module to the global objectglobal.Module=Module;})(this);
    // 5.2.1// A Practical Constructor(function(global){functionCtor(foo){this.foo=foo;returnthis;}Ctor.prototype.getFoo=function(){returnthis.foo;};Ctor.prototype.setFoo=function(val){return(this.foo=val);};// To call constructor's without `new`, you might do this:varctor=function(foo){returnnewCtor(foo);};// expose our constructor to the global objectglobal.ctor=ctor;})(this);
  5. Naming

    A. You are not a human code compiler/compressor, so don't try to be one.

    The following code is an example of egregious naming:

    // 6.A.1.1// Example of code with poor namesfunctionq(s){returndocument.querySelectorAll(s);}vari,a=[],els=q("#foo");for(i=0;i<els.length;i++){a.push(els[i]);}

    Without a doubt, you've written code like this - hopefully that ends today.

    Here's the same piece of logic, but with kinder, more thoughtful naming (and a readable structure):

    // 6.A.2.1// Example of code with improved namesfunctionquery(selector){returndocument.querySelectorAll(selector);}varidx=0,elements=[],matches=query("#foo"),length=matches.length;for(;idx<length;idx++){elements.push(matches[idx]);}

    A few additional naming pointers:

    // 6.A.3.1// Naming strings`dog`isastring// 6.A.3.2// Naming arrays`dogs`isanarrayof`dog`strings// 6.A.3.3// Naming functions, objects, instances, etccamelCase;functionandvardeclarations// 6.A.3.4// Naming constructors, prototypes, etc.PascalCase;constructorfunction// 6.A.3.5// Naming regular expressionsrDesc=//;// 6.A.3.6// From the Google Closure Library Style GuidefunctionNamesLikeThis;variableNamesLikeThis;ConstructorNamesLikeThis;EnumNamesLikeThis;methodNamesLikeThis;SYMBOLIC_CONSTANTS_LIKE_THIS;

    B. Faces ofthis

    Beyond the generally well known use cases ofcall andapply, always prefer.bind( this ) or a functional equivalent, for creatingBoundFunction definitions for later invocation. Only resort to aliasing when no preferable option is available.

    // 6.B.1functionDevice(opts){this.value=null;// open an async stream,// this will be called continuouslystream.read(opts.path,function(data){// Update this instance's current value// with the most recent value from the// data streamthis.value=data;}.bind(this));// Throttle the frequency of events emitted from// this Device instancesetInterval(function(){// Emit a throttled eventthis.emit("event");}.bind(this),opts.freq||100);}// Just pretend we've inherited EventEmitter ;)

    When unavailable, functional equivalents to.bind exist in many modern JavaScript libraries.

    // 6.B.2// eg. lodash/underscore, _.bind()functionDevice(opts){this.value=null;stream.read(opts.path,_.bind(function(data){this.value=data;},this));setInterval(_.bind(function(){this.emit("event");},this),opts.freq||100);}// eg. jQuery.proxyfunctionDevice(opts){this.value=null;stream.read(opts.path,jQuery.proxy(function(data){this.value=data;},this));setInterval(jQuery.proxy(function(){this.emit("event");},this),opts.freq||100);}// eg. dojo.hitchfunctionDevice(opts){this.value=null;stream.read(opts.path,dojo.hitch(this,function(data){this.value=data;}));setInterval(dojo.hitch(this,function(){this.emit("event");}),opts.freq||100);}

    As a last resort, create an alias tothis usingself as an Identifier. This is extremely bug prone and should be avoided whenever possible.

    // 6.B.3functionDevice(opts){varself=this;this.value=null;stream.read(opts.path,function(data){self.value=data;});setInterval(function(){self.emit("event");},opts.freq||100);}

    C. UsethisArg

    Several prototype methods of ES 5.1 built-ins come with a specialthisArg signature, which should be used whenever possible

    // 6.C.1varobj;obj={f:"foo",b:"bar",q:"qux"};Object.keys(obj).forEach(function(key){// |this| now refers to `obj`console.log(this[key]);},obj);// <-- the last arg is `thisArg`// Prints...// "foo"// "bar"// "qux"

    thisArg can be used withArray.prototype.every,Array.prototype.forEach,Array.prototype.some,Array.prototype.map,Array.prototype.filter

  6. Misc

    This section will serve to illustrate ideas and concepts that should not be considered dogma, but instead exists to encourage questioning practices in an attempt to find better ways to do common JavaScript programming tasks.

    A. Usingswitch should be avoided, modern method tracing will blacklist functions with switch statements

    There seems to be drastic improvements to the execution ofswitch statements in latest releases of Firefox and Chrome.http://jsperf.com/switch-vs-object-literal-vs-module

    Notable improvements can be witnessed here as well:#13

    // 7.A.1.1// An example switch statementswitch(foo){case"alpha":alpha();break;case"beta":beta();break;default:// something to default tobreak;}// 7.A.1.2// A alternate approach that supports composability and reusability is to// use an object to store "cases" and a function to delegate:varcases,delegator;// Example returns for illustration only.cases={alpha:function(){// statements// a returnreturn["Alpha",arguments.length];},beta:function(){// statements// a returnreturn["Beta",arguments.length];},_default:function(){// statements// a returnreturn["Default",arguments.length];}};delegator=function(){varargs,key,delegate;// Transform arguments list into an arrayargs=[].slice.call(arguments);// shift the case key from the argumentskey=args.shift();// Assign the default case handlerdelegate=cases._default;// Derive the method to delegate operation toif(cases.hasOwnProperty(key)){delegate=cases[key];}// The scope arg could be set to something specific,// in this case, |null| will sufficereturndelegate.apply(null,args);};// 7.A.1.3// Put the API in 7.A.1.2 to work:delegator("alpha",1,2,3,4,5);// [ "Alpha", 5 ]// Of course, the `case` key argument could easily be based// on some other arbitrary condition.varcaseKey,someUserInput;// Possibly some kind of form input?someUserInput=9;if(someUserInput>10){caseKey="alpha";}else{caseKey="beta";}// or...caseKey=someUserInput>10 ?"alpha" :"beta";// And then...delegator(caseKey,someUserInput);// [ "Beta", 1 ]// And of course...delegator();// [ "Default", 0 ]

    B. Early returns promote code readability with negligible performance difference

    // 7.B.1.1// Bad:functionreturnLate(foo){varret;if(foo){ret="foo";}else{ret="quux";}returnret;}// Good:functionreturnEarly(foo){if(foo){return"foo";}return"quux";}
  7. Native & Host Objects

    The basic principle here is:

    Don't do stupid shit and everything will be ok.

    To reinforce this concept, please watch the following presentation:

    “Everything is Permitted: Extending Built-ins” by Andrew Dupont (JSConf2011, Portland, Oregon)

    https://www.youtube.com/watch?v=xL3xCO7CLNM

  8. Comments

    Single line above the code that is subject

    Multiline is good

    End of line comments are prohibited!

    JSDoc style is good, but requires a significant time investment

  9. One Language Code

    Programs should be written in one language, whatever that language may be, as dictated by the maintainer or maintainers.

Appendix

Comma First.

Any project that cites this document as its base style guide will not accept comma first code formatting, unless explicitly specified otherwise by that project's author.


Creative Commons License
Principles of Writing Consistent, Idiomatic JavaScript byRick Waldron and Contributors is licensed under aCreative Commons Attribution 3.0 Unported License.
Based on a work atgithub.com/rwldrn/idiomatic.js.

About

Principles of Writing Consistent, Idiomatic JavaScript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp