Showing preview only (620K chars total). Download the full file or copy to clipboard to get everything.
Repository: rwaldron/idiomatic.js
Branch: master
Commit: d88432591ecf
Files: 24
Total size: 601.4 KB
Directory structure:
gitextract_w5co02kf/
├── .gitattributes
├── .gitignore
├── cc-license.md
├── contributors.md
├── readme.md
└── translations/
├── bg_BG/
│ └── readme.md
├── de_DE/
│ └── readme.md
├── es_ES/
│ └── readme.md
├── fr_FR/
│ └── readme.md
├── gr_GR/
│ └── readme.md
├── hi_HI/
│ └── readme.md
├── id_ID/
│ └── readme.md
├── it_IT/
│ └── readme.md
├── ja_JP/
│ └── readme.md
├── ko_KR/
│ └── readme.md
├── pl_PL/
│ └── readme.md
├── pt_BR/
│ └── readme.md
├── ro_RO/
│ └── readme.md
├── ru_RU/
│ └── readme.md
├── sr_SR/
│ └── readme.md
├── vi_VN/
│ └── readme.md
├── zh_CN/
│ └── readme.md
├── zh_TW/
│ └── readme.md
└── ср_СР/
└── readme.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
eol=lf
================================================
FILE: .gitignore
================================================
.DS_Store
*.swp
dist
kits/makefile-kit/dist
kits/jakefile-kit/dist
kits/jakefile-kit/node_modules
================================================
FILE: cc-license.md
================================================
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/80x15.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Principles of Writing Consistent, Idiomatic JavaScript</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/rwldrn/idiomatic.js" property="cc:attributionName" rel="cc:attributionURL">Rick Waldron and Contributors</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/rwldrn/idiomatic.js" rel="dct:source">github.com/rwldrn/idiomatic.js</a>.
This applies to all documents and translations in this repository.
================================================
FILE: contributors.md
================================================
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwldrn)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idan)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](http://www.opentutorials.org/course/167/1363) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Firede [@firede](https://twitter.com/firede) [github](https://github.com/firede)
* monkadd [github](https://github.com/monkadd)
* Stephan Lindauer [@stephanlindauer](http://twitter.com/stephanlindauer), [github](https://github.com/stephanlindauer)
* Thomas P [@dragon5689](https://twitter.com/dragon5689) [github](https://github.com/dragon5689)
* Yotam Ofek [@yotamofek](https://twitter.com/yotamofek) [github](https://github.com/yotamofek)
* Aleksandr Filatov [@greybax](http://twitter.com/greybax), [github](https://github.com/greybax)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Calvin Jeng [@l0ckys](http://twitter.com/l0ckys), [github](https://github.com/lockys)
* Richard Gibson [@gibson042](http://twitter.com/gibson042), [github](https://github.com/gibson042)
* Fesuy [github](https://github.com/fesuydev)
* Stephane Moreau [github](https://github.com/stmoreau)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
================================================
FILE: readme.md
================================================
# Principles of Writing Consistent, Idiomatic JavaScript
## 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.
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idan)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](https://opentutorials.org/course/245/1788) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Firede [@firede](https://twitter.com/firede) [github](https://github.com/firede)
* monkadd [github](https://github.com/monkadd)
* Stephan Lindauer [@stephanlindauer](http://twitter.com/stephanlindauer), [github](https://github.com/stephanlindauer)
* Thomas P [@dragon5689](https://twitter.com/dragon5689) [github](https://github.com/dragon5689)
* Yotam Ofek [@yotamofek](https://twitter.com/yotamofek) [github](https://github.com/yotamofek)
* Aleksandr Filatov [@greybax](http://twitter.com/greybax), [github](https://github.com/greybax)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Hao-Wei Jeng [@l0ckys](http://twitter.com/l0ckys), [github](https://github.com/lockys)
* Richard Gibson [@gibson042](http://twitter.com/gibson042), [github](https://github.com/gibson042)
* Fesuy [github](https://github.com/fesuydev)
* Stephane Moreau [github](https://github.com/stmoreau)
* Boris Nekezov [github](https://github.com/boris-nekezov)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## 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"
>_Rebecca_ _Murphey_
> ### "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."
>_Idan_ _Gazit_
## Translations
* [Bulgarian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/bg_BG)
* [German](https://github.com/rwldrn/idiomatic.js/tree/master/translations/de_DE)
* [French](https://github.com/rwldrn/idiomatic.js/tree/master/translations/fr_FR)
* [Spanish](https://github.com/rwldrn/idiomatic.js/tree/master/translations/es_ES)
* [Portuguese - Brazil](https://github.com/rwldrn/idiomatic.js/tree/master/translations/pt_BR)
* [Korean](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ko_KR)
* [日本語](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ja_JP)
* [Italian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/it_IT)
* [Russian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ru_RU)
* [Romanian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ro_RO)
* [简体中文](https://github.com/rwldrn/idiomatic.js/tree/master/translations/zh_CN)
* [Serbian - cyrilic alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ср_СР)
* [Serbian - latin alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/sr_SR)
* [繁體中文](https://github.com/rwaldron/idiomatic.js/tree/master/translations/zh_TW)
* [Indonesian](https://github.com/rwaldron/idiomatic.js/tree/master/translations/id_ID)
* [Greek](https://github.com/rwaldron/idiomatic.js/tree/master/translations/gr_GR)
* [Hindi](https://github.com/rwaldron/idiomatic.js/tree/master/translations/hi_HI)
## Important, Non-Idiomatic Stuff:
### Code Quality Tools, Resources & References
* [SonarQube](https://www.sonarqube.org/)
* [Plato](https://github.com/es-analysis/plato)
* [jsPerf](http://jsperf.com/)
* [jsFiddle](http://jsfiddle.net/)
* [Codepen](http://codepen.io/)
* [jsbin](http://jsbin.com/)
* [JavaScript Lint (JSL)](http://javascriptlint.com/)
* [jshint](http://jshint.com/)
* [jslint](http://jslint.org/)
* [eslint](http://eslint.org/)
* [jscs](https://www.npmjs.org/package/jscs)
* [jscodesniffer](https://www.npmjs.org/package/jscodesniffer)
* [Editorconfig](http://editorconfig.org/)
* [Hound](https://houndci.com/)
## Get Smart
### [Annotated ECMAScript 5.1](http://es5.github.com/)
### [EcmaScript Language Specification, 5.1 Edition](http://ecma-international.org/ecma-262/5.1/)
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.
* [Baseline For Front End Developers: 2015](https://rmurphey.com/posts/a-baseline-for-front-end-developers-2015/)
* [Eloquent JavaScript](http://eloquentjavascript.net/)
* [JavaScript, JavaScript](http://javascriptweblog.wordpress.com/)
* [Adventures in JavaScript Development](http://rmurphey.com/)
* [Perfection Kills](http://perfectionkills.com/)
* [Douglas Crockford's Wrrrld Wide Web](http://www.crockford.com)
* [JS Assessment](https://github.com/rmurphey/js-assessment)
### 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](https://github.com/gruntjs/grunt) by Ben Alman is second to none and has officially replaced the "kits/" directory of this repo.
### Test Facility
Projects _must_ 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.
* [QUnit](http://github.com/jquery/qunit)
* [Jasmine](https://github.com/pivotal/jasmine)
* [Vows](https://github.com/cloudhead/vows)
* [Mocha](https://github.com/visionmedia/mocha)
* [Hiro](http://hirojs.com/)
* [JsTestDriver](https://code.google.com/p/js-test-driver/)
* [Buster.js](http://busterjs.org/)
* [Sinon.js](http://sinonjs.org/)
* [Tape](https://github.com/substack/tape)
* [Jest](https://facebook.github.io/jest/)
## Table of Contents
* [Whitespace](#whitespace)
* [Beautiful Syntax](#spacing)
* [Type Checking (Courtesy jQuery Core Style Guidelines)](#type)
* [Conditional Evaluation](#cond)
* [Practical Style](#practical)
* [Naming](#naming)
* [Misc](#misc)
* [Native & Host Objects](#native)
* [Comments](#comments)
* [One Language Code](#language)
------------------------------------------------
## Preface
The following sections outline a _reasonable_ style guide for modern JavaScript development and are not meant to be prescriptive. The most important take-away is the **law 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. <a name="whitespace">Whitespace</a>
- Never mix spaces and tabs.
- When beginning a project, before you write any code, choose between soft indents (spaces) or real tabs, consider this **law**.
- 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
- Use [Editorconfig](http://editorconfig.org/) when possible. It supports most IDEs and handles most whitespace settings.
2. <a name="spacing">Beautiful Syntax</a>
A. Parens, Braces, Linebreaks
```javascript
// if/else/for/while/try always have spaces, braces and span multiple lines
// this encourages readability
// 2.A.1.1
// Examples of really cramped syntax
if(condition) doSomething();
while(condition) iterating++;
for(var i=0;i<100;i++) someIterativeFn();
// 2.A.1.1
// Use whitespace to promote readability
if ( condition ) {
// statements
}
while ( condition ) {
// statements
}
for ( var i = 0; i < 100; i++ ) {
// statements
}
// Even better:
var i,
length = 100;
for ( i = 0; i < length; i++ ) {
// statements
}
// Or...
var i = 0,
length = 100;
for ( ; i < length; i++ ) {
// statements
}
var prop;
for ( prop in object ) {
// statements
}
if ( true ) {
// statements
} else {
// statements
}
```
B. Assignments, Declarations, Functions ( Named, Expression, Constructor )
```javascript
// 2.B.1.1
// Variables
var foo = "bar",
num = 1,
undef;
// Literal notations:
var array = [],
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.
// Bad
var foo = "",
bar = "";
var qux;
// Good
var foo = "";
var bar = "";
var qux;
// or..
var foo = "",
bar = "",
qux;
// or..
var // Comment on these
foo = "",
bar = "",
quux;
// 2.B.1.3
// var statements should always be in the beginning of their respective scope (function).
// Bad
function foo() {
// some statements here
var bar = "",
qux;
}
// Good
function foo() {
var bar = "",
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).
// Bad
function foo() {
let foo,
bar;
if ( condition ) {
bar = "";
// statements
}
}
// Good
function foo() {
let foo;
if ( condition ) {
let bar = "";
// statements
}
}
```
```javascript
// 2.B.2.1
// Named Function Declaration
function foo( arg1, argN ) {
}
// Usage
foo( arg1, argN );
// 2.B.2.2
// Named Function Declaration
function square( number ) {
return number * number;
}
// Usage
square( 10 );
// Really contrived continuation passing style
function square( number, callback ) {
callback( number * number );
}
square( 10, function( square ) {
// callback statements
});
// 2.B.2.3
// Function Expression
var square = function( number ) {
// Return something valuable and relevant
return number * 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:
var factorial = function factorial( number ) {
if ( number < 2 ) {
return 1;
}
return number * factorial( number - 1 );
};
// 2.B.2.4
// Constructor Declaration
function FooBar( options ) {
this.options = options;
}
// Usage
var fooBar = new FooBar({ a: "alpha" });
fooBar.options;
// { a: "alpha" }
```
C. Exceptions, Slight Deviations
```javascript
// 2.C.1.1
// Functions with callbacks
foo(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 space
foo([ "alpha", "beta" ]);
// 2.C.1.2
// Function accepting an object, no space
foo({
a: "alpha",
b: "beta"
});
// Single argument string literal, no space
foo("bar");
// Expression parens, no space
if ( !("foo" in obj) ) {
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.
```javascript
// 2.D.1.1
if (condition) {
// statements
}
while (condition) {
// statements
}
for (var i = 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. What **ABSOLUTELY 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.
3. <a name="type">Type Checking (Courtesy jQuery Core Style Guidelines)</a>
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:
```html
<input type="text" id="foo-input" value="1">
```
```javascript
// 3.B.1.1
// `foo` has been declared with the value `0` and its type is `number`
var foo = 0;
// typeof foo;
// "number"
...
// Somewhere later in your code, you need to update `foo`
// with a new value derived from an input element
foo = 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:
```javascript
// 3.B.2.1
var number = 1,
string = "1",
bool = false;
number;
// 1
number + "";
// "1"
string;
// "1"
+string;
// 1
+string++;
// 1
string;
// 2
bool;
// false
+bool;
// 0
bool + "";
// "false"
```
```javascript
// 3.B.2.2
var number = 1,
string = "1",
bool = true;
string === number;
// false
string === number + "";
// true
+string === number;
// true
bool === number;
// false
+bool === number;
// true
bool === string;
// false
bool === !!string;
// true
```
```javascript
// 3.B.2.3
var array = [ "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 ) {
// ...
}
```
```javascript
// 3.B.2.4
var num = 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...
var neg = -2.5;
parseInt( neg, 10 );
// is the same as...
~~neg;
neg >> 0;
// All result in -2
// However...
neg >>> 0;
// Will result in 4294967294
```
4. <a name="cond">Conditional Evaluation</a>
```javascript
// 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 evaluation
if ( !foo ) ...
// ...Be careful, this will also match: 0, "", null, undefined, NaN
// If you _MUST_ test for a boolean false, then use
if ( 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 0
null == undefined
```
ALWAYS evaluate for the best, most accurate result - the above is a guideline, not a dogma.
```javascript
// 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, void 0
```
5. <a name="practical">Practical Style</a>
```javascript
// 5.1.1
// A Practical Module
(function( global ) {
var Module = (function() {
var data = "secret";
return {
// This is some boolean property
bool: true,
// Some string value
string: "a string",
// An array property
array: [ 1, 2, 3, 4 ],
// An object property
object: {
lang: "en-Us"
},
getData: function() {
// get the current value of `data`
return data;
},
setData: function( value ) {
// set the value of `data` and return it
return ( data = value );
}
};
})();
// Other things might happen here
// expose our module to the global object
global.Module = Module;
})( this );
```
```javascript
// 5.2.1
// A Practical Constructor
(function( global ) {
function Ctor( foo ) {
this.foo = foo;
return this;
}
Ctor.prototype.getFoo = function() {
return this.foo;
};
Ctor.prototype.setFoo = function( val ) {
return ( this.foo = val );
};
// To call constructor's without `new`, you might do this:
var ctor = function( foo ) {
return new Ctor( foo );
};
// expose our constructor to the global object
global.ctor = ctor;
})( this );
```
6. <a name="naming">Naming</a>
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:
```javascript
// 6.A.1.1
// Example of code with poor names
function q(s) {
return document.querySelectorAll(s);
}
var i,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):
```javascript
// 6.A.2.1
// Example of code with improved names
function query( selector ) {
return document.querySelectorAll( selector );
}
var idx = 0,
elements = [],
matches = query("#foo"),
length = matches.length;
for ( ; idx < length; idx++ ) {
elements.push( matches[ idx ] );
}
```
A few additional naming pointers:
```javascript
// 6.A.3.1
// Naming strings
`dog` is a string
// 6.A.3.2
// Naming arrays
`dogs` is an array of `dog` strings
// 6.A.3.3
// Naming functions, objects, instances, etc
camelCase; function and var declarations
// 6.A.3.4
// Naming constructors, prototypes, etc.
PascalCase; constructor function
// 6.A.3.5
// Naming regular expressions
rDesc = //;
// 6.A.3.6
// From the Google Closure Library Style Guide
functionNamesLikeThis;
variableNamesLikeThis;
ConstructorNamesLikeThis;
EnumNamesLikeThis;
methodNamesLikeThis;
SYMBOLIC_CONSTANTS_LIKE_THIS;
```
B. Faces of `this`
Beyond the generally well known use cases of `call` and `apply`, always prefer `.bind( this )` or a functional equivalent, for creating `BoundFunction` definitions for later invocation. Only resort to aliasing when no preferable option is available.
```javascript
// 6.B.1
function Device( opts ) {
this.value = null;
// open an async stream,
// this will be called continuously
stream.read( opts.path, function( data ) {
// Update this instance's current value
// with the most recent value from the
// data stream
this.value = data;
}.bind(this) );
// Throttle the frequency of events emitted from
// this Device instance
setInterval(function() {
// Emit a throttled event
this.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.
```javascript
// 6.B.2
// eg. lodash/underscore, _.bind()
function Device( 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.proxy
function Device( 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.hitch
function Device( 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 to `this` using `self` as an Identifier. This is extremely bug prone and should be avoided whenever possible.
```javascript
// 6.B.3
function Device( opts ) {
var self = this;
this.value = null;
stream.read( opts.path, function( data ) {
self.value = data;
});
setInterval(function() {
self.emit("event");
}, opts.freq || 100 );
}
```
C. Use `thisArg`
Several prototype methods of ES 5.1 built-ins come with a special `thisArg` signature, which should be used whenever possible
```javascript
// 6.C.1
var obj;
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 with `Array.prototype.every`, `Array.prototype.forEach`, `Array.prototype.some`, `Array.prototype.map`, `Array.prototype.filter`
7. <a name="misc">Misc</a>
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. Using `switch` should be avoided, modern method tracing will blacklist functions with switch statements
There seems to be drastic improvements to the execution of `switch` 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:
https://github.com/rwldrn/idiomatic.js/issues/13
```javascript
// 7.A.1.1
// An example switch statement
switch( foo ) {
case "alpha":
alpha();
break;
case "beta":
beta();
break;
default:
// something to default to
break;
}
// 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:
var cases, delegator;
// Example returns for illustration only.
cases = {
alpha: function() {
// statements
// a return
return [ "Alpha", arguments.length ];
},
beta: function() {
// statements
// a return
return [ "Beta", arguments.length ];
},
_default: function() {
// statements
// a return
return [ "Default", arguments.length ];
}
};
delegator = function() {
var args, key, delegate;
// Transform arguments list into an array
args = [].slice.call( arguments );
// shift the case key from the arguments
key = args.shift();
// Assign the default case handler
delegate = cases._default;
// Derive the method to delegate operation to
if ( cases.hasOwnProperty( key ) ) {
delegate = cases[ key ];
}
// The scope arg could be set to something specific,
// in this case, |null| will suffice
return delegate.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.
var caseKey, 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
```javascript
// 7.B.1.1
// Bad:
function returnLate( foo ) {
var ret;
if ( foo ) {
ret = "foo";
} else {
ret = "quux";
}
return ret;
}
// Good:
function returnEarly( foo ) {
if ( foo ) {
return "foo";
}
return "quux";
}
```
8. <a name="native">Native & Host Objects</a>
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
9. <a name="comments">Comments</a>
#### 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
10. <a name="language">One Language Code</a>
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.
----------
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/80x15.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Principles of Writing Consistent, Idiomatic JavaScript</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/rwldrn/idiomatic.js" property="cc:attributionName" rel="cc:attributionURL">Rick Waldron and Contributors</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/rwldrn/idiomatic.js" rel="dct:source">github.com/rwldrn/idiomatic.js</a>.
================================================
FILE: translations/bg_BG/readme.md
================================================
# Принципи на консистентно и идиоматично писане на JavaScript
## Това е "жив" документ и нови идеи за подобряване на кода са винаги добре дошли. Допринесете: fork, clone, branch, commit, push, pull request.
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idan)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](https://opentutorials.org/course/245/1788) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Firede [@firede](https://twitter.com/firede) [github](https://github.com/firede)
* monkadd [github](https://github.com/monkadd)
* Stephan Lindauer [@stephanlindauer](http://twitter.com/stephanlindauer), [github](https://github.com/stephanlindauer)
* Thomas P [@dragon5689](https://twitter.com/dragon5689) [github](https://github.com/dragon5689)
* Yotam Ofek [@yotamofek](https://twitter.com/yotamofek) [github](https://github.com/yotamofek)
* Aleksandr Filatov [@greybax](http://twitter.com/greybax), [github](https://github.com/greybax)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Hao-Wei Jeng [@l0ckys](http://twitter.com/l0ckys), [github](https://github.com/lockys)
* Richard Gibson [@gibson042](http://twitter.com/gibson042), [github](https://github.com/gibson042)
* Fesuy [github](https://github.com/fesuydev)
* Stephane Moreau [github](https://github.com/stmoreau)
* Boris Nekezov [github](https://github.com/boris-nekezov)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## Целият код във всяка кодова база трябва да изглежда като писано от един човек, няма значение колко души са допринесли.
### Последващия списък изтъква практиките, които използвам в всичкия ми код, на който съм оригинален автор; участия в проекти, които съм създал трябва да следват тези напътствия.
### Нямам намерение да налагам моите предпочитания за стил на кода или проекти на други хора; ако има наличие на съществуващ общ стил, той трябва да се спазва.
> ### "Спорове за стилове са безсмислени. Трябва да има ръководство за стила и трябва да го спазвате"
>_Rebecca_ _Murphey_
> ### "Част от това да си добър ръководител на един успешен проект е да осъзнаете, че писането на код за вас е лоша идея. Ако хиляди души използват вашия код, тогава пишете кода ви максилнално ясно, а не по вашето лично предпочитание."
>_Idan_ _Gazit_
## Translations
* [ORIGINAL](https://github.com/rwldrn/idiomatic.js/)
* [Bulgarian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/bg_BG)
* [German](https://github.com/rwldrn/idiomatic.js/tree/master/translations/de_DE)
* [French](https://github.com/rwldrn/idiomatic.js/tree/master/translations/fr_FR)
* [Spanish](https://github.com/rwldrn/idiomatic.js/tree/master/translations/es_ES)
* [Portuguese - Brazil](https://github.com/rwldrn/idiomatic.js/tree/master/translations/pt_BR)
* [Korean](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ko_KR)
* [日本語](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ja_JP)
* [Italian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/it_IT)
* [Russian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ru_RU)
* [Romanian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ro_RO)
* [简体中文](https://github.com/rwldrn/idiomatic.js/tree/master/translations/zh_CN)
* [Serbian - cyrilic alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ср_СР)
* [Serbian - latin alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/sr_SR)
* [繁體中文](https://github.com/rwaldron/idiomatic.js/tree/master/translations/zh_TW)
* [Indonesian](https://github.com/rwaldron/idiomatic.js/tree/master/translations/id_ID)
* [Greek](https://github.com/rwaldron/idiomatic.js/tree/master/translations/gr_GR)
* [Hindi](https://github.com/rwaldron/idiomatic.js/tree/master/translations/hi_HI)
## Важни, Не-Идиоматични Неща:
### Инструменти за Качество на Кода, Ресурси & Референции
* [JavaScript Plugin](http://docs.codehaus.org/display/SONAR/JavaScript+Plugin) for [Sonar](http://www.sonarsource.org/)
* [Plato](https://github.com/es-analysis/plato)
* [jsPerf](http://jsperf.com/)
* [jsFiddle](http://jsfiddle.net/)
* [Codepen](http://codepen.io/)
* [jsbin](http://jsbin.com/)
* [JavaScript Lint (JSL)](http://javascriptlint.com/)
* [jshint](http://jshint.com/)
* [jslint](http://jslint.org/)
* [eslint](http://eslint.org/)
* [jscs](https://www.npmjs.org/package/jscs)
* [jscodesniffer](https://www.npmjs.org/package/jscodesniffer)
* [Editorconfig](http://editorconfig.org/)
* [Hound](https://houndci.com/)
## Станете Умни
### [Annotated ECMAScript 5.1](http://es5.github.com/)
### [Спецификация на Езика EcmaScript, Издание 5.1](http://ecma-international.org/ecma-262/5.1/)
Последващото трябва да се вземе под внимание 1) недовършено, и 2) *ИЗИСКВА СЕ ЧЕТЕНЕ*. Не винаги съм съгласен със стила написан от авторите по-долу, но едно нещо е сигурно: Те са консистентни. Нещо повече, това са авторитети на езика.
* [Baseline For Front End Developers: 2015](http://rmurphey.com/blog/2015/03/23/a-baseline-for-front-end-developers-2015/)
* [Eloquent JavaScript](http://eloquentjavascript.net/)
* [JavaScript, JavaScript](http://javascriptweblog.wordpress.com/)
* [Adventures in JavaScript Development](http://rmurphey.com/)
* [Perfection Kills](http://perfectionkills.com/)
* [Douglas Crockford's Wrrrld Wide Web](http://www.crockford.com)
* [JS Assessment](https://github.com/rmurphey/js-assessment)
### Процес на компилация и деплойване
Проектите винаги трябва да включат някои общи средства, чрез които източникът да бъде свързан, тестван и компресиран при подготовка за производствена употреба. За тази задача, [grunt](https://github.com/gruntjs/grunt) на Бен Алман е най-добрата от всички официални заместители на папката "kits/" в това хранилище.
### Тестова база
Проектите трябва да включват някаква форма на единица, референция, имплементация или функционално тестване. Демострационни случаи на употреба НЕ СЕ КВАЛИФИЦИРАТ като "тестове". По-долу има списък със тестови рамки, нито една от които не е одобрена повече от другата.
* [QUnit](http://github.com/jquery/qunit)
* [Jasmine](https://github.com/pivotal/jasmine)
* [Vows](https://github.com/cloudhead/vows)
* [Mocha](https://github.com/visionmedia/mocha)
* [Hiro](http://hirojs.com/)
* [JsTestDriver](https://code.google.com/p/js-test-driver/)
* [Buster.js](http://busterjs.org/)
* [Sinon.js](http://sinonjs.org/)
* [Tape](https://github.com/substack/tape)
* [Jest](https://facebook.github.io/jest/)
## Съдържание
* [Whitespace](#whitespace)
* [Beautiful Syntax](#spacing)
* [Type Checking (Courtesy jQuery Core Style Guidelines)](#type)
* [Conditional Evaluation](#cond)
* [Practical Style](#practical)
* [Naming](#naming)
* [Misc](#misc)
* [Native & Host Objects](#native)
* [Comments](#comments)
* [One Language Code](#language)
------------------------------------------------
## Предговор
Следващите раздели посочват едно разумно ръководство на стил за съвременна разработка на JavaScript и не е предназначен за норматив. Най-важната част е **закона за постоянност на стила на кода**. Каквото и да изберете като стил за вашия проект, трябва да се счита за закон. Използвайте този документ като напътствие на вашето отдаване към проекта ви за консистентност на стила на кода, четимост и поддържане.
## Манифест на идиоматичния стил
1. <a name="whitespace">Празно пространство</a>
- Никога не смесвайте спейсове и табове.
- Когато започнете един проект, преди да почнете да пишете какъвто и да е код, изберете между меки отсъпи (интервали) или реални табулации, считайте го за **закон**
- За четимост, винаги препоръчвам да зададете размера на отстъпа на вашия редактор на два знака — което означава два интервала или два интервала, представляващи истинска табулация.
- Винаги работете с включена настройка "покажи скрити", ако редактора ви я поддържа. Предимствата на тази практика са:
- Усилена консистенция
- Премахване на интервал в края на реда
- Премахване на празни редове
- Комитите и разликите в кода са по-лесни за четене
- Използвайте [Editorconfig](http://editorconfig.org/) когато е възможно. Поддържа повечето IDEs и обработва повечето настройки за празно пространство.
2. <a name="spacing">Красив синтаксис</a>
A. Parens, Braces, Linebreaks
А. Скоби, Фигурни Скоби, Пренасяне на редовете
```javascript
// if/else/for/while/try винаги имат интервали между тях, къдравите скоби и разделението между секциите са на множество редове
// това подобрява четимостта
// 2.A.1.1
// Примери за наистина нечетлив синтаксис
if(condition) doSomething();
while(condition) iterating++;
for(var i=0;i<100;i++) someIterativeFn();
// 2.A.1.1
// Използвайте интервали за да повишите четимостта
if ( condition ) {
// изрази
}
while ( condition ) {
// изрази
}
for ( var i = 0; i < 100; i++ ) {
// изрази
}
// Още по-добре:
var i,
length = 100;
for ( i = 0; i < length; i++ ) {
// изрази
}
// Или...
var i = 0,
length = 100;
for ( ; i < length; i++ ) {
// изрази
}
var prop;
for ( prop in object ) {
// изрази
}
if ( true ) {
// изрази
} else {
// изрази
}
```
B. Прислояване, Декларации, Функции ( Именувани, Изрази, Конструктори)
```javascript
// 2.B.1.1
// Променливи
var foo = "bar",
num = 1,
undef;
// Литерална нотация:
var array = [],
object = {};
// 2.B.1.2
// Използването на само един `var` на всеки обхват (функция) или по един `var` на всяка променлива,
// повишава четимостта и пази вашия списък на декларации от безредие.
// Използването по един `var` на всяка променлива можете да контролирате по-добре версиите
// и освен това улеснява разместването на редовете.
// Един `var` на всеки обхват улеснява намирането на недекларирани променливи,
// които могат да станат подразбиращи се глобални.
// Изберете по-добрия подход за вашия проект и никога не го смесвайте
// Лош пример
var foo = "",
bar = "";
var qux;
// Добър пример
var foo = "";
var bar = "";
var qux;
// или..
var foo = "",
bar = "",
qux;
// или..
var // Коментар на тези
foo = "",
bar = "",
quux;
// 2.B.1.3
// Операторите 'var' винаги трябва да са в началото на техния съответен обxват (функция).
// Лош пример
function foo() {
// някакви изрази
var bar = "",
qux;
}
// Добър пример
function foo() {
var bar = "",
qux;
// всички изрази след декларацията на променливите
}
// 2.B.1.4
// 'const' и `let`, от ECMAScript 6, също трябва да са в горната част на техния обхват (блоков).
// Лош пример
function foo() {
let foo,
bar;
if ( condition ) {
bar = "";
// изрази
}
}
// Добър пример
function foo() {
let foo;
if ( condition ) {
let bar = "";
// изрази
}
}
```
```javascript
// 2.B.2.1
// Деклариране на именувана функция
function foo( arg1, argN ) {
}
// Използване
foo( arg1, argN );
// 2.B.2.2
// Деклариране на именувана функция
function square( number ) {
return number * number;
}
// Използване
square( 10 );
// Много измислен стил на подаване на параметри
function square( number, callback ) {
callback( number * number );
}
square( 10, function( square ) {
// изрази с обратно извикване
});
// 2.B.2.3
// Функция-Израз
var square = function( number ) {
// Върнете нещо важно и релевантно
return number * number;
};
// Функция-Израз с Идентификатор
// Тази предпочитана форма има добавената стойност
// и името му ще бъде видимо в стека на функционалните обаждания:
var factorial = function factorial( number ) {
if ( number < 2 ) {
return 1;
}
return number * factorial( number - 1 );
};
// 2.B.2.4
// Деклариране на Конструктор
function FooBar( options ) {
this.options = options;
}
// Използване
var fooBar = new FooBar({ a: "alpha" });
fooBar.options;
// { a: "alpha" }
```
C. Изключения, леки отклонения
```javascript
// 2.C.1.1
// Функции с обратно извикване
foo(function() {
// Забележете, че няма интервали между първата скоба
// на изпълненото фунционално извикване и думата "function"
});
// Функция приемаща масив като параметър, без интервал
foo([ "alpha", "beta" ]);
// 2.C.1.2
// Функция приемаща обект като параметър, без интервал
foo({
a: "alpha",
b: "beta"
});
// Единичен низ като параметър, също без интервал
foo("bar");
// Съдържание във вътрешни скоби, също без интервал
if ( !("foo" in obj) ) {
obj = (obj.bar || defaults).baz;
}
```
D. Консистентността винаги побеждава
В секции 2.A-2.C, правилата за интервали са изложени като препоръка с по-проста и по-извисена цел: консистентност.
Важно е да се отбележи, че предпочитанията за форматиране, такива като "вътрешно пространство", трябва да се считат за незадължителни, но само един стил трябва да съществува из целия код на вашия проект.
```javascript
// 2.D.1.1
if (condition) {
// изрази
}
while (condition) {
// изрази
}
for (var i = 0; i < 100; i++) {
// изрази
}
if (true) {
// изрази
} else {
// изрази
}
```
E. Кавички
Независимо от това дали предпочитате единични или двойни кавички, няма разлика в това как JavaScript ги парсва. Това което **АБСОЛЮТНО ТРЯБВА** да се наложи е консистентност. **Никога не смесвайте кавичките в един и същи проект. Изберете един стил и се придържайте към него.**
F. Край на Редовете и Празни Редове
Пространствата могат да развалят разликите и да направят промените невъзможни за четене. Помислете да включите "pre-commit" кука, която да премахне автоматично пространството на края на реда и празните пространства на редовете.
3. <a name="type">Type Checking (Courtesy jQuery Core Style Guidelines)</a>
A. Типове
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:
Глобални променливи:
typeof variable === "undefined"
Локални променливи:
variable === undefined
Свойства:
object.prop === undefined
object.hasOwnProperty( prop )
"prop" in object
B. Прехвърляне на Типове
Представете си следното...
Даден ви е следния HTML:
```html
<input type="text" id="foo-input" value="1">
```
```javascript
// 3.B.1.1
// `foo` е деклариран със стойност `0` и неговия тип е `number`
var foo = 0;
// typeof foo;
// "number"
...
// Някъде по-късно във вашия код, трябва да обновите `foo`
// с нова стойност взета от елемента 'input'
foo = document.getElementById("foo-input").value;
// Ако сега тествате 'typeof foo`, резултатът ще бъде 'string'
// Това означава, че ако имате логика, която тества 'foo' като тази:
if ( foo === 1 ) {
importantTask();
}
// `importantTask()` няма никога да бъде достигнат дори и `foo` да има стойност "1"
// 3.B.1.2
// Можете да избегнете проблеми като използвате умно конвертиране в унарните оператори + и -:
foo = +document.getElementById("foo-input").value;
// ^ унарния оператор + ще преобразува десния си операнд в тип 'number'
// typeof foo;
// "number"
if ( foo === 1 ) {
importantTask();
}
// `importantTask()` ще бъде извикана
```
Ето няколко често срещани примера за прехвърляне на типове:
```javascript
// 3.B.2.1
var number = 1,
string = "1",
bool = false;
number;
// 1
number + "";
// "1"
string;
// "1"
+string;
// 1
+string++;
// 1
string;
// 2
bool;
// false
+bool;
// 0
bool + "";
// "false"
```
```javascript
// 3.B.2.2
var number = 1,
string = "1",
bool = true;
string === number;
// false
string === number + "";
// true
+string === number;
// true
bool === number;
// false
+bool === number;
// true
bool === string;
// false
bool === !!string;
// true
```
```javascript
// 3.B.2.3
var array = [ "a", "b", "c" ];
!!~array.indexOf("a");
// true
!!~array.indexOf("b");
// true
!!~array.indexOf("c");
// true
!!~array.indexOf("d");
// false
// Забележете, че горните примери може да се считат за "ненужно умни"
// За предпочитане е очевидния подход да сравнявате върнатата стойност на
// indexOf, по този начин:
if ( array.indexOf( "a" ) >= 0 ) {
// ...
}
```
```javascript
// 3.B.2.4
var num = 2.5;
parseInt( num, 10 );
// е съшото като ...
~~num;
num >> 0;
num >>> 0;
// Във всички случаи резултатът е равен на 2
// Помнете, че отрицателните числа ще бъдат обработени различно ...
var neg = -2.5;
parseInt( neg, 10 );
// е същото като...
~~neg;
neg >> 0;
// Във всички случаи резултатът е равен на -2
// Въпреки че при...
neg >>> 0;
// Резултата ще е 4294967294
```
4. <a name="cond">Условна Проверка</a>
```javascript
// 4.1.1
// Проверете дали масивът има дължина,
// вместо:
if ( array.length > 0 ) ...
// ...проверявайте за истина, по този начин:
if ( array.length ) ...
// 4.1.2
// Проверете дали масива е празен,
// вместо:
if ( array.length === 0 ) ...
// ...проверявайте за вярност, по този начин:
if ( !array.length ) ...
// 4.1.3
// Проверете дали низа не е празен,
// вместо:
if ( string !== "" ) ...
// ...проверявайте за вярност, по този начин:
if ( string ) ...
// 4.1.4
// Проверете дали низа _е_ празен,
// вместо:
if ( string === "" ) ...
// ...проверявайте дали израдът е неверен, по този начин:
if ( !string ) ...
// 4.1.5
// Проверете дали тази референция е вярна,
// вместо:
if ( foo === true ) ...
// ...проверете, възползвайки се от вградените възможности:
if ( foo ) ...
// 4.1.6
// Проверете дали тази референция е невярна,
// вместо:
if ( foo === false ) ...
// ...проверете, използвайки отрицание
if ( !foo ) ...
// ...Внимавайте, това важи и за: 0, "", null, undefined, NaN
// Ако _трябва_ да тествате за булево невярно, тогава използвайте
if ( foo === false ) ...
// 4.1.7
// Когато проверявате дали е null или undefined, но НЕ Е false, "" или 0,
// вместо това:
if ( foo === null || foo === undefined ) ...
// ...използвайте оператора ==:
if ( foo == null ) ...
// Помнете, че използвайки оператора == с `null` важи И ЗА ДВЕТЕ `null` и `undefined`
// но не `false ', "" или 0
null == undefined
```
ВИНАГИ проверявайте за най-добрия и точен резултат - горното е ръководство, не догма.
```javascript
// 4.2.1
// Преобразуване на типове и бележки за проверяване
// За предпочитане е да използвате `===` вместо `==` (освен ако конкретния случай не изисква слабо типизирана оценка)
// === проверява и типа, т.е.:
"1" === 1;
// false
// == не проверява типа, т.е.:
"1" == 1;
// true
// 4.2.2
// Логически изрази, Вярни & Невярни
// Логически изрази:
true, false
// Вярни:
"foo", 1
// Невярни:
"", 0, null, undefined, NaN, void 0
```
5. <a name="practical">Стил на Практика</a>
```javascript
// 5.1.1
// Практичен модул
(function( global ) {
var Module = (function() {
var data = "secret";
return {
// Логическо свойство
bool: true,
// Стойност от тип низ
string: "a string",
// Свойство - масив
array: [ 1, 2, 3, 4 ],
// Свойство - обект
object: {
lang: "bg-BG"
},
getData: function() {
// вземете текущата стойност на променливата `data`
return data;
},
setData: function( value ) {
// присвоете стойността на `data` и я върнете
return ( data = value );
}
};
})();
// Други декларации
// добавяме нашия модул към глобалния обект
global.Module = Module;
})( this );
```
```javascript
// 5.2.1
// Практичен Конструктор
(function( global ) {
function Ctor( foo ) {
this.foo = foo;
return this;
}
Ctor.prototype.getFoo = function() {
return this.foo;
};
Ctor.prototype.setFoo = function( val ) {
return ( this.foo = val );
};
// За да извикате конструктора без `new`, можете да направите това:
var ctor = function( foo ) {
return new Ctor( foo );
};
// добави нашия конструктор към глобалния обект
global.ctor = ctor;
})( this );
```
6. <a name="naming">Наименуване</a>
A. Вие не сте човешки компилатор/компресор на код, затова не се опитвайте да бъдете такъв.
Последващия код е пример за лошо именуване:
```javascript
// 6.A.1.1
// Пример за код с лоши имена
function q(s) {
return document.querySelectorAll(s);
}
var i,a=[],els=q("#foo");
for(i=0;i<els.length;i++){a.push(els[i]);}
```
Без съмнение сте писали код като този - дано това приключи днес.
Сега същото парче логика, но с по-добро, по-смислено именуване (и четима структура):
```javascript
// 6.A.2.1
// Пример на кода с подобрени имена
function query( selector ) {
return document.querySelectorAll( selector );
}
var idx = 0,
elements = [],
matches = query("#foo"),
length = matches.length;
for ( ; idx < length; idx++ ) {
elements.push( matches[ idx ] );
}
```
Още няколко съвета за именуване на променливи::
```javascript
// 6.A.3.1
// Именуване на низове
`dog` is a string
// 6.A.3.2
// Именуване на масиви
`dogs` is an array of `dog` strings
// 6.A.3.3
// Именуване на фукнции, обекти, инстанции, и т.н.
camelCase; function and var declarations
// 6.A.3.4
// Именуване на конструктори, прототипи и т.н.
PascalCase; constructor function
// 6.A.3.5
// Именуване на регулярни изрази
rDesc = //;
// 6.A.3.6
// Из Ръководство по стила Google Closure Library
functionNamesLikeThis;
variableNamesLikeThis;
ConstructorNamesLikeThis;
EnumNamesLikeThis;
methodNamesLikeThis;
SYMBOLIC_CONSTANTS_LIKE_THIS;
```
B. Лица на `this`
Извън общоизвестните случаи на `call` и `apply`, винаги избирайте `.bind( this )` или фунционалния му еквивалент, за създаване на дефиниция `BoundFunction` за по-късно извикване. Създаването на псевдоним е в краен случай, ако други решения не са подходящи.
```javascript
// 6.B.1
function Device( opts ) {
this.value = null;
// Отворете асинхронен поток,
// това ще се извиква продължително
stream.read( opts.path, function( data ) {
// Обновете текущата стойност на инстанцията
// с последната стойност от
// потока на данни
this.value = data;
}.bind(this) );
// Ограничете честотата на събитията изпратени от
// инстанцията на Device
setInterval(function() {
// Изпращане на събитие
this.emit("event");
}.bind(this), opts.freq || 100 );
}
// Просто се преструвайте, че сме наследили EventEmitter ;)
```
Когато не е достъпен фукнционалния еквивалент на `.bind` съществува в много модерни JavaScript библиотеки.
```javascript
// 6.B.2
// например lodash/underscore, _.bind()
function Device( 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 );
}
// например jQuery.proxy
function Device( 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 );
}
// например dojo.hitch
function Device( 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 );
}
```
В краен случай, създайте алиас на `this` използвайки `self` като идентификатор. Това е изключително податливо на грешки и трябва да се избягва, когато е възможно.
```javascript
// 6.B.3
function Device( opts ) {
var self = this;
this.value = null;
stream.read( opts.path, function( data ) {
self.value = data;
});
setInterval(function() {
self.emit("event");
}, opts.freq || 100 );
}
```
C. Използване на `thisArg`
Няколко прототипни метода вградени в ES 5.1 идват със специалния `thisArg`, който трябва да се използва когато е възможно
```javascript
// 6.C.1
var obj;
obj = { f: "foo", b: "bar", q: "qux" };
Object.keys( obj ).forEach(function( key ) {
// |this| сочи към `obj`
console.log( this[ key ] );
}, obj ); // <-- последния аргумент е `thisArg`
// Ще изпечата...
// "foo"
// "bar"
// "qux"
```
`thisArg` може да се използва `Array.prototype.every`, `Array.prototype.forEach`, `Array.prototype.some`, `Array.prototype.map`, `Array.prototype.filter`
7. <a name="misc">Разни</a>
Този раздел ще служи за илюстриране на идеи и концепции, които не трябва да се считат за догма, вместо това съществува за да даде под съмнение практиките в опит да се намери по-добри начини за изпълнение, на често срещани JavaScript задачи.
A. Използването на `switch` трябва да се избягва, тъй като съвременния метод за отстраняване на грешки ще скрие повикванията на функции, които го използват.
Изглежда че последните версии на браузърите Firefox и Chrome имат значителни подобрения в работата на функциите, които използват `switch`.
http://jsperf.com/switch-vs-object-literal-vs-module
Забележими подобрения могат да се видят също и тук:
https://github.com/rwldrn/idiomatic.js/issues/13
```javascript
// 7.A.1.1
// Пример на оператора switch
switch( foo ) {
case "alpha":
alpha();
break;
case "beta":
beta();
break;
default:
// код по подразбиране
break;
}
// 7.A.1.2
// Алтернативен подход, който подкрепя използваемостта и повторната употреба е да
// се използва обект за съхранение на "случаи" и функция за делегация
var cases, delegator;
// Примерът връща само с илюстративни цели.
cases = {
alpha: function() {
// изрази
// връщане
return [ "Alpha", arguments.length ];
},
beta: function() {
// изрази
// връщане
return [ "Beta", arguments.length ];
},
_default: function() {
// изрази
// връщане
return [ "Default", arguments.length ];
}
};
delegator = function() {
var args, key, delegate;
// Трансформиране на списъка с аргументите в масив
args = [].slice.call( arguments );
// Променяне на ключа на случая от аргументите
key = args.shift();
// Определяне на ключа по подразбиране
delegate = cases._default;
// Извличане на метода за да делегиране на операция
if ( cases.hasOwnProperty( key ) ) {
delegate = cases[ key ];
}
// Обхватния аргумент може да бъде зададен към нещо специфични,
// в този случай, |null| ще бъде достатъчно
return delegate.apply( null, args );
};
// 7.A.1.3
// Сложете Апито в 7.A.1.2 да работи:
delegator( "alpha", 1, 2, 3, 4, 5 );
// [ "Alpha", 5 ]
// Разбира се, ключовият аргумент на `случая` може да се основава лесно
// при някакво друго произволно условие.
var caseKey, someUserInput;
// Вероятно някакво поле на форма?
someUserInput = 9;
if ( someUserInput > 10 ) {
caseKey = "alpha";
} else {
caseKey = "beta";
}
// или...
caseKey = someUserInput > 10 ? "alpha" : "beta";
// И тогава...
delegator( caseKey, someUserInput );
// [ "Beta", 1 ]
// И разбира се...
delegator();
// [ "Default", 0 ]
```
B. Ранните връщания подобряват четимостта на кода с незначителна разлика в производителността
```javascript
// 7.B.1.1
// Лош пример:
function returnLate( foo ) {
var ret;
if ( foo ) {
ret = "foo";
} else {
ret = "quux";
}
return ret;
}
// Добър пример:
function returnEarly( foo ) {
if ( foo ) {
return "foo";
}
return "quux";
}
```
8. <a name="native">"Родни" и "Чужди" обекти</a>
Основния принципт тук е:
### Не правете глупости и всичко ще бъде наред.
За да подсилите тази концепция, моля гледайте последващата презентация:
#### “Everything is Permitted: Extending Built-ins” от Андрю Дюпонт (JSConf2011, Портланд, Орегон)
https://www.youtube.com/watch?v=xL3xCO7CLNM
9. <a name="comments">Коментари</a>
#### Едноредов коментар над кода, за който е предназначен
#### Многоредови коментари също са добре дошли
#### Коментарите в края на реда са забранени!
#### Стила JSDoc е добър, но изисква да се инвестира значително време
10. <a name="language">Код на Един Език </a>
Програмите трябва да бъдат написани на един език, независимо какъв е той, както се изисква от хората, които поддържат кода.
## Приложение
### Първа Запетая.
Всеки проект, който се отнася до този документ като основно ръководство за стил, няма да приеме форматирането на кода "първа запетая", освен ако авторът на проекта конкретно не посочи това.
----------
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/80x15.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Principles of Writing Consistent, Idiomatic JavaScript</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/rwldrn/idiomatic.js" property="cc:attributionName" rel="cc:attributionURL">Rick Waldron and Contributors</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/rwldrn/idiomatic.js" rel="dct:source">github.com/rwldrn/idiomatic.js</a>.
================================================
FILE: translations/de_DE/readme.md
================================================
# Grundsätze für das Schreiben von konsequentem und idiomatischem JavaScript
## Dies ist ein lebendiges Dokument und neue Ideen, die den Code in unserem Umfeld verbessern, sind immer willkommen. Tragt dazu bei: "fork", "clone", "branch", "commit", "push", "pull request".
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idangazit)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](http://www.opentutorials.org/course/167/1363) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Stephane Moreau [github](https://github.com/stmoreau)
* Boris Nekezov [github](https://github.com/boris-nekezov)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## Code sollte grundsätzlich so aussehen, als wäre er von einer einzigen Person geschrieben worden, völlig egal, wie viele letztlich daran gearbeitet haben.
### Das folgende Dokument zeigt Praktiken, die sich in jedem Code, den ich ursprünglich geschrieben habe, wiederfinden. Sämtliche Beiträge für Projekte, die ich kreiert habe, sollten diesen Praktiken folgen.
### Ich möchte anderen Leuten nicht meine Vorlieben aufzwängen; wenn es bereits einen geläufigen Style gibt, sollte dieser respektiert werden.
> "Dass es eine schlechte Idee ist, nur für sich selbst Code zu schreiben, ist etwas, was man als guter Betreuer eines erfolgreichen Projektes begreifen muss™. Wenn tausende Leute deinen Code benutzen, dann schreibe deinen Code möglichst klar und übersichtlich, nicht einfach nur nach deinen persönlichen Vorlieben." - Idan Gazit
## Übersetzungen
* [ORIGINAL](https://github.com/rwldrn/idiomatic.js/)
* [Bulgarian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/bg_BG)
* [German](https://github.com/rwldrn/idiomatic.js/tree/master/translations/de_DE)
* [French](https://github.com/rwldrn/idiomatic.js/tree/master/translations/fr_FR)
* [Spanish](https://github.com/rwldrn/idiomatic.js/tree/master/translations/es_ES)
* [Portuguese - Brazil](https://github.com/rwldrn/idiomatic.js/tree/master/translations/pt_BR)
* [Korean](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ko_KR)
* [Japanese](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ja_JP)
* [Italian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/it_IT)
* [Russian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ru_RU)
* [Romanian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ro_RO)
* [简体中文](https://github.com/rwldrn/idiomatic.js/tree/master/translations/zh_CN)
* [Serbian - cyrilic alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ср_СР)
* [Serbian - latin aplphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/sr_SR)
* [Greek](https://github.com/rwaldron/idiomatic.js/tree/master/translations/gr_GR)
* [Hindi](https://github.com/rwaldron/idiomatic.js/tree/master/translations/hi_HI)
## Wichtiger, nicht-idiomatischer Kram:
### Code-Qualität: Tolle Werkzeuge, Ressourcen und Referenzen
* [JavaScript Plugin](http://docs.codehaus.org/display/SONAR/JavaScript+Plugin) für [Sonar](http://www.sonarsource.org/)
* [Plato](https://github.com/jsoverson/plato)
* [jsPerf](http://jsperf.com/)
* [jsFiddle](http://jsfiddle.net/)
* [jsbin](http://jsbin.com/)
* [JavaScript Lint (JSL)](http://javascriptlint.com/)
* [jshint](http://jshint.com/)
* [jslint](http://jslint.org/)
* [Editorconfig](http://editorconfig.org/)
[Leveraging Code Quality Tools by Anton Kovalyov](http://anton.kovalyov.net/slides/gothamjs/)
### Schlau werden
[http://es5.github.com/](http://es5.github.com/)
Bei den folgenden Ressourcen sollte berücksichtigt werden, dass sie 1) unvollständig und 2) *PFLICHTLEKTÜREN* sind. Ich stimme dem beschriebenen Style der unten stehenden Autoren nicht immer zu, aber eins ist sicher: Sie sind konsequent. Außerdem sind dies echte Autoritäten in dieser Sprache.
* [Baseline For Front End Developers](http://rmurphey.com/blog/2012/04/12/a-baseline-for-front-end-developers/)
* [Eloquent JavaScript](http://eloquentjavascript.net/)
* [JavaScript, JavaScript](http://javascriptweblog.wordpress.com/)
* [Adventures in JavaScript Development](http://rmurphey.com/)
* [Perfection Kills](http://perfectionkills.com/)
* [Douglas Crockford's Wrrrld Wide Web](http://www.crockford.com)
* [JS Assessment](https://github.com/rmurphey/js-assessment)
### Build- und Deployment-Prozess
Jedes Projekt sollte Komponenten verwenden, um den Code zu linten, testen oder komprimieren, um so im Produktivbereich eingesetzt zu werden. Ben Alan hat für diese Aufgabe [grunt](https://github.com/cowboy/grunt) entworfen und damit offiziell das "kits/" Verzeichnis aus diesem Repository ersetzt.
### Hilfsmittel zum Testen
Projekte _müssen_ irgendeine Art von Unit-, Reference, Implementation- oder Functional-Testing enthalten. Demonstrationen von Anwendungsfällen reichen als Test nicht aus. Die unten aufgeführte Liste beinhaltet eine Menge nützlicher Test-Frameworks.
* [QUnit](http://github.com/jquery/qunit)
* [Jasmine](https://github.com/pivotal/jasmine)
* [Vows](https://github.com/cloudhead/vows)
* [Mocha](https://github.com/visionmedia/mocha)
* [Hiro](http://hirojs.com/)
* [JsTestDriver](https://code.google.com/p/js-test-driver/)
* [Buster.js](http://busterjs.org/)
## Inhaltsverzeichnis
* [Whitespace](#whitespace)
* [Schöne Syntax](#spacing)
* [Typprüfung](#type)
* [Bedingte Auswertungen](#cond)
* [Praktischer Style](#practical)
* [Bezeichnungen](#naming)
* [Sonstiges](#misc)
* [Native & Host Objekte](#native)
* [Kommentare](#comments)
* [Einsprachiger Code](#language)
------------------------------------------------
## Vorwort
Die folgenden Bereiche zeigen einen vertretbaren Style Guide für moderne JavaScript-Entwicklung. Es handelt sich dabei aber nicht etwa um eine Art Vorschrift. Das Wichtigste, was man aber mitnehmen sollte, ist das **Gesetz der Stilkonsistenz**. Egal, welchen Stil du für dein Projekt wählst, er sollte als Regel betrachtet werden.
## Idiomatisches Style Manifest
1. <a name="whitespace">Whitespace</a>
- Mische niemals Spaces und Tabs
- Bevor du mit einem Projekt beginnst und Code schreibst, entscheide dich zwischen Soft Intends (Spaces) oder echten Tabs.
- Für die Lesbarkeit empfehle ich, die Einrückung immer auf die Größe von zwei Zeichen zu setzen. Das bedeutet zwei Spaces repräsentieren einen echten Tab.
- Wenn dein Editor die Konfiguration "Steuerzeichen einblenden" unterstützt, solltest du sie einschalten. Das bringt folgende Vorteile mit sich:
- Erzwungene Konsistenz
- Löschen von Whitespaces am Ende der Zeile
- Löschen von leeren "Whitespace Zeilen"
- Commits und Diffs sind einfacher zu lesen
2. <a name="spacing">Schöne Syntax</a>
A. Leerzeichen, geschweifte Klammern und Zeilenumbrüche
```javascript
// if/else/for/while/try enthalten immer Leerzeichen, geschweifte Klammern
// und erstrecken sich über mehrere Zeilen
// Das trägt zur Lesbarkeit bei
// 2.A.1.1
// Beispiele von echt verkrampfter Syntax
if(Bedingung) machWas();
while(Bedingung) iterieren++;
for(var i=0;i<100;i++) irgendeineIterativeFunktion();
// 2.A.1.1
// Benutze Whitespaces um die Lesbarkeit zu verbessern
if ( Bedingung ) {
// statements
}
while ( Bedingung ) {
// statements
}
for ( var i = 0; i < 100; i++ ) {
// statements
}
// Noch besser:
var i,
length = 100;
for ( i = 0; i < length; i++ ) {
// statements
}
// Oder...
var i = 0,
length = 100;
for ( ; i < length; i++ ) {
// statements
}
var prop;
for ( prop in object ) {
// statements
}
if ( true ) {
// statements
} else {
// statements
}
```
B. Zuweisungen, Deklarationen, Funktionen (Benamte, Ausdrücke, Kontruktoren)
```javascript
// 2.B.1.1
// Variablen
var foo = "bar",
num = 1,
undef;
// Literalnotationen:
var array = [],
object = {};
// 2.B.1.2
// Nur einmal `var` pro Scope (Funktion) zu verwenden, verbessert die Lesbarkeit
// und hält deine Deklarationsliste frei von Verwirrungen
// Schlecht
var foo = "";
var bar = "";
var qux;
// Gut
var foo = "",
bar = "",
quux;
// Oder..
var // Hier kommentieren
foo = "",
bar = "",
quux;
// 2.B.1.3
// var Statements sollten immer an den Anfang ihres respektiven Scopes (Funktion)
// Das gleiche gilt für const und let aus ECMAScript 6
// Schlecht
function foo() {
// irgendwas
var bar = "",
qux;
}
// Gut
function foo() {
var bar = "",
qux;
// alle Statements nach der var-Deklaration
}
```
```javascript
// 2.B.2.1
// Benannte Funktionsdeklaration
function foo( arg1, argN ) {
}
// Benutzung
foo( arg1, argN );
// 2.B.2.2
// Benannte Funktionsdeklaration
function quadrat(zahl) {
return zahl * zahl;
}
// Benutzung
quadrat( 10 );
function quadrat( zahl, callback ) {
callback( zahl * zahl);
}
quadrat( 10, function (square) {
// callback Statements
});
// 2.B.2.3
// Funktionsausdruck
var quadrat = function ( zahl ) {
// gibt irgendwas zurück
return zahl * zahl;
}
// Funktionsausdruck mit Bezeichner
// Diese Form hat den Vorteil, dass sie sich selbst aufrufen kann
// und der Bezeichner im Stack Trace zufinden ist
var factorial = function factorial( zahl ) {
if ( zahl < 2 ) {
return 1;
}
return zahl * factorial( zahl-1 );
};
// 2.B.2.4
// Konstrukturdeklaration
function fooBar ( options) {
this.options = options;
}
// Benutzung
var fooBar = new FooBar({ a: "alpha" });
fooBar.options:
// { a: "alpha" }
```
C. Ausnahmen, Leichte Abweichungen
```javascript
// 2.C.1.1
// Funktionen mit Callbacks
foo(function() {
// Achte darauf, dass es hier keinen extra Whitespace nach der ersten Klammer gibt
});
// Funktionen, die ein Array erwarten, haben keine Whitespaces auf erster Ebene
foo([ "alpha", "beta" ]);
// 2.C.1.2
// Funktionen, die ein Object erwarten, haben ebenfalls keine Spaces
foo({
a: "alpha",
b: "beta"
});
// Einzelner Stringliteral, kein Space
foo("bar");
// Inner gruppierte Klammern, kein Space
if ( !("foo" in obj) ) {
}
```
D. Konsistenz gewinnt immer
In Sektion 2.A-2.C, sieht man den Vorteil durch die Verwendung von Whitespaces, Lesbarkeit und Konsistenz.
Es ist immer wichtig darauf zu achten, Formatierung-Vorlieben, wie der Whitespace innerhalb der Klammern, als optional zu betrachten. Trotzdem sollte sich eine Formatierung durch den ganzen Quelltext einheitlich erstrecken.
```javascript
// 2.D.1.1
if (Bedingung) {
// statements
}
while (Bedingung) {
// statements
}
for (var i = 0; i < 100; i++) {
// statements
}
if (true) {
// statements
} else {
// statements
}
```
E. Anführungszeichen
Ob du jetzt einfache oder doppelte Anführungszeichen bevorzugst ist völlig egal. JavaScript parst sie immer gleich. Das Einzige, worauf auf jeden Fall geachtet werden **MUSS**, ist Konsistenz. **Vermische niemals Anführungszeichen innerhalb eines Projekts.** Suche dir einen Stil aus und bleib dabei.
F. Zeilenenden und leere Zeilen
Whitespaces können diffs ruinieren. Pre-Commit-Hooks können verwendet werden, um End-Of-Line-Whitespaces zu leere Zeilen zu entfernen.
3. <a name="type">Typprüfung</a>
A. Primitive Typen
String:
typeof variable === "string"
Number:
typeof variable === "number"
Boolean:
typeof variable === "boolean"
Object:
typeof variable === "object"
Array:
Array.isArray( arrayArtigesObjekt )
(wenn möglich)
Node:
elem.nodeType === 1
null:
variable === null
null oder undefined:
variable == null
undefined:
Globale Variablen:
typeof variable === "undefined"
Lokale Variablen:
variable === undefined
Properties:
object.prop === undefined
object.hasOwnProperty( prop )
"prop" in object
B. Gezwungene Typen
Betrachten wir folgende Auswirkungen...
Dieses HTML ist gegeben:
```html
<input type="text" id="foo-input" value="1">
```
```js
// 3.B.1.1
// `foo` wurde mit dem Wert `0` deklariert und ist vom Typ `number`
var foo = 0;
// typeof foo;
// "number"
...
// Später im Code musst du `foo` mit einem neuen Wert aus dem input-Element überschreiben
foo = document.getElementById("foo-input").value;
// Wenn du jetzt mit `typeof foo` testen möchtest, wird das Ergebnis `string` sein
// Das bedeutet, wenn du Logik hast, die `foo` so testet:
if ( foo === 1 ) {
wichtigeFunktion();
}
// `wichtigeFunktion()` würde niemals ausgeführt werden, selbst wenn `foo` den wert "1" hätte
// 3.B.1.2
// Du kannst diese Probleme umgehen, indem du die Typen mit unären - oder + - Operationen erzwingst:
foo = +document.getElementById("foo-input").value;
// ^ unärer + - Operator konvertiert den rechten Operanden in eine Zahl (Number)
// typeof foo;
// "number"
if ( foo === 1 ) {
wichtigeFunktion();
}
// `wichtigeFunktion()` würde ausgeführt
```
Hier sind ein paar Fälle in denen Erzwingungen verwendet werden:
```javascript
// 3.B.2.1
var number = 1,
string = "1",
bool = false;
number;
// 1
number + "";
// "1"
string;
// "1"
+string;
// 1
+string++;
// 1
string;
// 2
bool;
// false
+bool;
// 0
bool + "";
// "false"
```
```javascript
// 3.B.2.2
var number = 1,
string = "1",
bool = true;
string === number;
// false
string === number + "";
// true
+string === number;
// true
bool === number;
// false
+bool === number;
// true
bool === string;
// false
bool == !!string;
// true
```
```javascript
// 3.B.2.3
var array = [ "a", "b", "c" ];
!!~array.indexOf("a");
// true
!!~array.indexOf("b");
// true
!!~array.indexOf("c");
// true
!!~array.indexOf("d");
// false
```
```javascript
// 3.B.2.3
var num = 2.5;
parseInt( num, 10 );
// ist das Gleiche wie...
~~num;
num >> 0;
num >>> 0;
// Gibt 2 zurück
// Denke daran, dass negative Zahlen anders behandelt werden...
var neg = -2.5;
parseInt( neg, 10 );
// Ist das Gleiche wie...
~~neg;
neg >> 0;
// Gibt 2 zurück
// Wie dem auch sei...
neg >>> 0;
// Gibt 4294967294 zurück
```
4. <a name="cond">Bedingte Auswertungen</a>
```javascript
//4.1.1
// Wenn du nur prüfen willst, ob ein Array eine Länge hat, ...
if ( array.length > 0 ) ...
// prüfe es so:
if ( array.length ) ...
// 4.1.2
// Wenn du nur prüfen willst, ob ein Array leer ist...
if ( array.length === 0 ) ...
// mach es so:
if ( !array.length ) ...
// 4.1.3
// Wenn du prüfen willst, ob ein String nich leer ist
if ( string !== "" ) ...
// ... mach es so:
if ( string ) ...
// 4.1.4
// Wenn du prüfen willst, ob ein String leer ist...
if ( string === "" ) ...
// ... mach es so:
if ( !string ) ...
// 4.1.5
// Wenn du prüfen willst, ob eine Referenz false ist...
if ( foo === false ) ...
// ... nutze die Negierung um eine eine true-Auswertung zu erzwingen
if ( !foo ) ...
// ... aber vorsicht, das würde auch bei 0, "", null, undefined und NaN funktionieren
// Wenn du für einen boolsches false testen _musst_, mach's so:
if ( foo === false ) ...
// 4.1.7
// Wenn du eine Referenz prüfen möchtest, die möglicherweise null oder undefined, aber NICHT false ist...
if ( foo === null || foo === undefined ) ...
// ... nutze den Vorteil der Typerzwingung
if ( foo == null ) ...
// Denk daran, '==' wird 'null' auf 'null' UND 'undefined' matchen, aber nicht 'false', "" oder 0
null == undefined
```
5. <a name="practical">Praktischer Style</a>
```javascript
// 5.1.1
// Ein angewandtes Modul
(function( global ) {
var Module = (function() {
var data = "secret";
return {
// Eine boolesche Eigenschaft
bool: true,
// Ein Stringwert
string: "a string",
// Eine Array-Eigenschaft
array: [ 1, 2, 3, 4 ],
// Eine Objekteigenschaft
object: {
lang: "en-Us"
},
getData: function() {
// gibt den Wert von data
return data;
},
setData: function( value ) {
// setzt den Wert von data
return ( data = value );
}
};
})();
// Hier könnten weitere Dinge passieren
// Das Modul im globalen Namensraum verfügbar machen
global.Module = Module;
})( this );
```
```javascript
// 5.2.1
// Ein angewandter Konstruktor
(function( global ) {
function Ctor( foo ) {
this.foo = foo;
return this;
}
Ctor.prototype.getFoo = function() {
return this.foo;
};
Ctor.prototype.setFoo = function( val ) {
return ( this.foo = val );
};
// Um den Konstruktor ohne `new` aufzurufen, machst du möglicherweise sowas:
var ctor = function( foo ) {
return new Ctor( foo );
};
// Konstruktor im globalen Namensraum verfügbar machen
global.ctor = ctor;
})( this );
```
6. <a name="naming">Bezeichnungen</a>
Du bist kein Compiler, also versuch nicht, einer zu sein.
Der folgende Code ist ein Beispiel für entsetzlich schlechte Bezeichnungen:
```javascript
// 6.1.1
// Beispielcode mit schlechten Bezeichnungen
function q(s) {
return document.querySelectorAll(s);
}
var i,a=[],els=q("#foo");
for(i=0;i<els.length;i++){a.push(els[i]);}
```
Du hast ohne Zweifel schon mal solchen Code geschrieben - das hört heute auf.
Hier ist der gleiche Code, nur klarer, durchdachter und mit einer lesbaren Struktur:
```javascript
// 6.2.1
// Beispielcode mit verbesserten Bezeichnungen
function query( selector ) {
return document.querySelectorAll( selector );
}
var idx = 0,
elements = [],
matches = query("#foo"),
length = matches.length;
for( ; idx < length; idx++ ){
elements.push( matches[ idx ] );
}
```
Ein paar weitere Punkte bezüglich der Bezeichnungen:
```javascript
// 6.3.1
// Strings benennen
`dog` ist ein String
// 6.3.2
// Arrays benennen
`dogs` ist ein Array bestehend aus `dog` Strings
// 6.3.3
// Funktionen, Objekte, Instanzen etc. benennen
camelCase; Funktions- und var- Deklarationen
// 6.3.4
// Konstruktoren und Prototypen benennen
PascalCase; Konstruktorfunktion
// 6.3.5
// Reguläre Ausdrücke benennen
rDesc = //;
// 6.3.6
// Aus dem Google Closure Library Style Guide
functionNamesLikeThis;
variableNamesLikeThis;
ConstructorNamesLikeThis;
EnumNamesLikeThis;
methodNamesLikeThis;
SYMBOLIC_CONSTANTS_LIKE_THIS;
```
7. <a name="misc">Sonstiges</a>
Diese Sektion stellt Ideen und Konzepte dar, die nicht dogmatisch betrachtet werden sollten. Sie sollen fragliche Praktiken fördern, die immer wieder in der JavaScript Programmierung auftauchen.
A. `switch` Statements sollten vermieden werden.
Es scheint starke Verbesserungen bei der Ausführung von `switch` Statements im neuesten Firefox und Chrome zu geben.
http://jsperf.com/switch-vs-object-literal-vs-module
https://github.com/rwldrn/idiomatic.js/issues/13
```javascript
// 7.A.1.1
// Ein Beispiel Switch Statement
switch( foo ) {
case "alpha":
alpha();
break;
case "beta":
beta();
break;
default:
// Fallback
break;
}
// 7.A.1.2
// Besser sollte man aber ein Objektliteral oder Modul verwenden:
var switchObj = {
alpha: function() {
// statements
// a return
},
beta: function() {
// statements
// a return
},
_default: function() {
// statements
// a return
}
};
var switchModule = (function () {
return {
alpha: function() {
// statements
// a return
},
beta: function() {
// statements
// a return
},
_default: function() {
// statements
// a return
}
};
})();
// 7.A.1.3
// Wenn `foo` eine Eigenschaft von `switchObj` oder `switchModule` ist, führe diesen Code hier aus..
( Object.hasOwnProperty.call( switchObj, foo ) && switchObj[ foo ] || switchObj._default )( args );
( Object.hasOwnProperty.call( switchObj, foo ) && switchModule[ foo ] || switchModule._default )( args );
// Wenn du auf die Werte von `foo` vertraust und weißt, was drin ist,
// kannst du die ODER-Prüfung weglassen und den Code einfach nur ausführen:
switchObj[ foo ]( args );
switchModule[ foo ]( args );
// Dieses Muster sorgt außerdem für Wiederverwendbarkeit von Code
```
B. Frühzeitige Rückgaben sorgen für lesbareren Code mit einem kleinen Performance-Unterschied
```javascript
// 7.B.1.1
// Schlecht:
function returnLate( foo ) {
var ret;
if ( foo ) {
ret = "foo";
} else {
ret = "quux";
}
return ret;
}
// Gut:
function returnEarly( foo ) {
if ( foo ) {
return "foo";
}
return "quux";
}
```
8. <a name="native">Native & Host Objekte</a>
Das grundsätzliche Prinzip ist hier:
### Mach keinen Unsinn und alles wird gut.
Um das Ganze noch mehr zu stärken, schaue dir folgende Präsentationen an:
#### “Everything is Permitted: Extending Built-ins” by Andrew Dupont (JSConf2011, Portland, Oregon)
https://www.youtube.com/watch?v=xL3xCO7CLNM
9. <a name="comments">Kommentare</a>
* Mehrzeilige Kommentare sind gut
* Kommentare am Zeilenende sind untersagt!
* JSDoc Style Kommentare sind gut, aber erfordern mehr Zeit.
10. <a name="language">Einsprachiger Code</a>
Programme sollten in der Sprache geschrieben sein, egal um welche Sprache es sich handelt, die der Projektbetreuer vorgibt.
## Anhang
### Comma First.
Jedes Projekt, welches dieses Dokument als grundsätzlichen Style Guide verwendet, akzeptiert keine Comma-First-Formatierung, solange es nicht explizit vom Projektautor angegeben wurde.
----------
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/80x15.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Grundsätze for das schreiben vonkonsequentem und idiomatischem JavaScript</span> von <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/rwldrn/idiomatic.js" property="cc:attributionName" rel="cc:attributionURL">Rick Waldron und Mitwirkenden</a> ist lizensiert unter <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>.<br />Basierend auf einer Arbeit unter <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/rwldrn/idiomatic.js" rel="dct:source">github.com/rwldrn/idiomatic.js</a>.
================================================
FILE: translations/es_ES/readme.md
================================================
# Principios para escribir JavaScript consistente e idiomático
## Este es un documento vivo, y nuevas ideas para mejorar el código que nos rodea son siempre bienvenidas. Contribuye: forkea, clona, branchea, commitea, pushea y haz alguna pull request.
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idan)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](http://www.opentutorials.org/course/167/1363) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Firede [@firede](https://twitter.com/firede) [github](https://github.com/firede)
* monkadd [github](https://github.com/monkadd)
* Stephan Lindauer [@stephanlindauer](http://twitter.com/stephanlindauer), [github](https://github.com/stephanlindauer)
* Thomas P [@dragon5689](https://twitter.com/dragon5689) [github](https://github.com/dragon5689)
* Yotam Ofek [@yotamofek](https://twitter.com/yotamofek) [github](https://github.com/yotamofek)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Stephane Moreau [github](https://github.com/stmoreau)
* Boris Nekezov [github](https://github.com/boris-nekezov)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## Todo el código en cualquier proyecto debería verse como si una sola persona lo hubiera escrito, sin importar cuánta gente haya contribuído.
### La lista que se presenta a continuación destaca las prácticas que uso en todo el código del que soy autor, y las contribuciones a todos los proyectos que he creado deben seguir estas prácticas.
### No intento imponer mis preferencias de estilo en el código de otras personas; si tienen un algún estilo común, homogéneo, esto debería ser respetado.
> ### "Argumentación por sobre el estilo, no tiene sentido. Debería existir una guía de estilo, y tú deberías seguirla"
>_Rebecca_ _Murphey_
> ### "Parte de ser un buen colaborador en un proyecto exitoso es darse cuenta que escribir código para uno mismo es una Mala Idea™. Si miles de personas están utilizando tu código, entonces escríbelo para máxima claridad, no tu preferencia personal de cómo ser inteligente aunque dentro de las especificaciones. "
>_Idan_ _Gazit_
## Traducciones
* [ORIGINAL](https://github.com/rwldrn/idiomatic.js/)
* [Bulgarian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/bg_BG)
* [German](https://github.com/rwldrn/idiomatic.js/tree/master/translations/de_DE)
* [French](https://github.com/rwldrn/idiomatic.js/tree/master/translations/fr_FR)
* [Spanish](https://github.com/rwldrn/idiomatic.js/tree/master/translations/es_ES)
* [Portuguese - Brazil](https://github.com/rwldrn/idiomatic.js/tree/master/translations/pt_BR)
* [Korean](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ko_KR)
* [Japanese](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ja_JP)
* [Italian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/it_IT)
* [Russian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ru_RU)
* [Romanian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ro_RO)
* [简体中文](https://github.com/rwldrn/idiomatic.js/tree/master/translations/zh_CN)
* [Serbian - cyrilic alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ср_СР)
* [Serbian - latin aplphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/sr_SR)
* [Greek](https://github.com/rwaldron/idiomatic.js/tree/master/translations/gr_GR)
* [Hindi](https://github.com/rwaldron/idiomatic.js/tree/master/translations/hi_HI)
## Cosas importantes, no relacionadas directamente con el JS idiomático:
### Calidad de código: herramientas, recursos y referencias
* [Plug-in de JavaScript](http://docs.codehaus.org/display/SONAR/JavaScript+Plugin) para [Sonar](http://www.sonarsource.org/)
* [Plato](https://github.com/jsoverson/plato)
* [jsPerf](http://jsperf.com/)
* [jsFiddle](http://jsfiddle.net/)
* [jsbin](http://jsbin.com/)
* [JavaScript Lint (JSL)](http://javascriptlint.com/)
* [jshint](http://jshint.com/)
* [jslint](http://jslint.org/)
* [Editorconfig](http://editorconfig.org/)
### Conociendo mejor el lenguaje
### [Annotated ECMAScript 5.1](http://es5.github.com/)
### [EcmaScript Language Specification, 5.1 Edition](http://ecma-international.org/ecma-262/5.1/)
Los siguientes artículos son 1) incompletos y 2) *OBLIGATORIOS*. No siempre estoy de acuerdo con el estilo escrito por sus autores, pero una cosa es cierta: son consistentes. Además, son autoridades en el lenguaje.
* [Baseline For Front End Developers](http://rmurphey.com/blog/2012/04/12/a-baseline-for-front-end-developers/)
* [Eloquent JavaScript](http://eloquentjavascript.net/)
* [JavaScript, JavaScript](http://javascriptweblog.wordpress.com/)
* [Adventures in JavaScript Development](http://rmurphey.com/)
* [Perfection Kills](http://perfectionkills.com/)
* [Douglas Crockford's Wrrrld Wide Web](http://www.crockford.com)
* [JS Assessment](https://github.com/rmurphey/js-assessment)
(Todos estos artículos están en inglés)
### Proceso de Build y Deployment
Los proyectos deberían tratar de incluir siempre algún mecanismo para que el código pueda ser verificado, comprimido y optimizado para su uso en producción. Para esta tarea, [grunt](https://github.com/gruntjs/grunt) por Ben Alman es la primera en ganar una gran popularidad, y ha reemplazado oficialmente la carpeta "kits/" que había en este repo.
### Testing
Los proyectos _deben_ incluir alguna forma de prueba (test unitario, test funcional, etc). Las demos NO CUENTAN como "tests". A continuación, una lista de frameworks para testing, ninguno de los cuales recomiendo más que otro.
* [QUnit](https://github.com/jquery/qunit)
* [Jasmine](https://github.com/pivotal/jasmine)
* [Vows](https://github.com/cloudhead/vows)
* [Mocha](https://github.com/visionmedia/mocha)
* [Hiro](http://hirojs.com/)
* [JsTestDriver](https://code.google.com/p/js-test-driver/)
* [Buster.js](http://busterjs.org/)
* [Sinon.js](http://sinonjs.org/)
## Tabla de contenidos
* [Espacios en blanco](#whitespace)
* [Beautiful Syntax](#spacing)
* [Comprobación de tipos (Cortesía de la guía de estilo de jQuery)](#type)
* [Evaluación condicional](#cond)
* [Estilo práctico](#practical)
* [Naming](#naming)
* [Varios](#misc)
* [Native & Host Objects](#native)
* [Comentarios](#comments)
* [Código en un lenguaje](#language)
------------------------------------------------
## Prólogo
Las siguientes secciones delinean una guía de estilos _razonable_ para un desarrollo moderno de JavaScript, y no intentan ser prescriptivas. Lo más importante es la **ley de consistencia de estilo de código**. Cualquiera sea el estilo que escojas para tu proyecto debería ser considerado ley. Piensa en este documento como una declaración del compromiso para con la consistencia de estilo, legibilidad y mantenibilidad.
## Manifiesto de estilo idiomático
1. <a name="whitespace">Espacios en blanco</a>
- Nunca mezclar espacios y tabulaciones.
- Al comenzar un proyecto, antes de escribir código, escoger entre indentación blanda (espacios), o tabulaciones — Esto es **LEY**.
- Para mayor legibilidad, siempre recomiendo ajustar las preferencias de tu editor para que el tamaño de la indentación sea de dos caracteres — esto significa, usar dos espacios, o que dos espacios representen una tabulación.
- Si tu editor lo soporta, trabajar siempre con la preferencia activada para que se muestren los caracteres invisibles. Los beneficios de esta práctica son:
- Reforzar la consistencia.
- Eliminar el espacio en blanco del fin de línea.
- Eliminar los espacios en blanco de las líneas vacías.
- Commits y diffs más fáciles de leer.
2. <a name="spacing">Sintaxis elegante</a>
A. Paréntesis, Llaves, Fines de línea
```javascript
// if/else/for/while/try siempre tienen espacios y se extienden a múltiples líneas
// Esto mejora la legibilidad
// 2.A.1.1
// Ejemplos de sintaxis toda comprimida
if(condition) doSomething();
while(condition) iterating++;
for(var i=0;i<100;i++) someIterativeFn();
// 2.A.1.1
// Uso de espacios para mejorar la legibilidad
if ( condition ) {
// statements
}
while ( condition ) {
// statements
}
for ( var i = 0; i < 100; i++ ) {
// statements
}
// Aún mejor:
var i,
length = 100;
for ( i = 0; i < length; i++ ) {
// statements
}
// O...
var i = 0,
length = 100;
for ( ; i < length; i++ ) {
// statements
}
var prop;
for ( prop in object ) {
// statements
}
if ( true ) {
// statements
} else {
// statements
}
```
B. Asignaciones, Declaraciones, Funciones (Nombradas, Expresiones, Constructores)
```javascript
// 2.B.1.1
// Variables
var foo = "bar",
num = 1,
undef;
// Notaciones literales:
var array = [],
object = {};
// 2.B.1.2
// Usando solo una instancia de `var` por scope (o sea, dentro de la función), mejora la legibilidad
// y mantiene tu lista de declaraciones claras (también ahorra de tipear un poco más)
// Mal
var foo = "";
var bar = "";
var qux;
// Bien
var foo = "",
bar = "",
quux;
// o..
var // comentar en éstos
foo = "",
bar = "",
quux;
// 2.B.1.3
// sentencias `var` deberían estar siempre al principio de su respectivo scope (alcance), que sería la función.
// Mal
function foo() {
// algunas sentencias
var bar = "",
qux;
}
// Bien
function foo() {
var bar = "",
qux;
// todas las sentencias luego de la declaración de variables.
}
// 2.B.1.4
// const y let, de ECMAScript 6, de la misma manera deberían aparecer al principio de su scope (alcance), que sería el bloque.
// Mal
function foo() {
let foo,
bar;
if (condition) {
bar = "";
// sentencias
}
}
// Bien
function foo() {
let foo;
if (condition) {
let bar = "";
// sentencias
}
}
```
```javascript
// 2.B.2.1
// Declaración De Función Nombrada
function foo( arg1, argN ) {
}
// Uso
foo( arg1, argN );
// 2.B.2.2
// Declaración De Función Nombrada
function square( number ) {
return number * number;
}
// Uso
square( 10 );
// Really contrived continuation passing style
function square( number, callback ) {
callback( number * number );
}
square( 10, function( square ) {
// callback statements
});
// 2.B.2.3
// Expresión de función
var square = function( number ) {
// Retornar algo relevante y con valor agregado
return number * number;
};
// Expresión de función con identificador
// Esta forma es preferida porque tiene el valor agregado de
// poder ser llamada a sí misma y ser identificable en el seguimiento de la pila (MUY útil para debugging):
var factorial = function factorial( number ) {
if ( number < 2 ) {
return 1;
}
return number * factorial( number-1 );
};
// 2.B.2.4
// Declaración de Constructor
function FooBar( options ) {
this.options = options;
}
// Uso
var fooBar = new FooBar({ a: "alpha" });
fooBar.options;
// { a: "alpha" }
```
C. Algunas excepciones
```javascript
// 2.C.1.1
// Funciones con callbacks
foo(function() {
// Como se ve, no hay espacio entre el primer paréntesis
// y la palabra "function"
});
// Función que acepta un Array como parámetro, sin espacio entre ([
foo([ "alpha", "beta" ]);
// 2.C.1.2
// Función que acepta un objeto, sin espacio
foo({
a: "alpha",
b: "beta"
});
// Argumento único de tipo string, sin espacio
foo("bar");
// Grupo de paréntesis dentro de paréntesis, sin espacio
if ( !("foo" in obj) ) {
}
```
D. La consistencia siempre gana
En las secciones 2.A-2.C, las reglas para los espacios son puestas con un objetivo más simple y con un propósito más general: consistencia.
Es importante destacar que algunas preferencias de formato, deberían ser consideradas opcionales, pero solo un estilo debería existir a través de todo el código fuente de tu proyecto.
```javascript
// 2.D.1.1
if (condition) {
// sentencias
}
while (condition) {
// sentencias
}
for (var i = 0; i < 100; i++) {
// sentencias
}
if (true) {
// sentencias
} else {
// sentencias
}
```
E. Comillas
Si prefieres comillas simples o dobles no debería importar, no hay diferencias ya que JavaScript las parsea. Lo que **ABSOLUTAMENTE DEBE** ser cumplido es la consistencia. **Nunca mezclar comillas en el mismo proyecto. Elegir un estilo y cumplirlo a rajatabla.**
F. Fin de línea y líneas vacías
Espacios en blanco pueden arruinar diffs y hacer los cambios imposibles de leer. Considera agregar algún mecanismo para remover automáticamente los espacios que se encuentran al final de la línea o en líneas vacías.
3. <a name="type">Verificación de tipos (Cortesía de la guía de estilo de jQuery)</a>
A. Tipos
String:
typeof variable === "string"
Number:
typeof variable === "number"
Boolean:
typeof variable === "boolean"
Object:
typeof variable === "object"
Array:
Array.isArray( arrayLikeObject )
(cuando sea posible / hay implementaciones que no tienen esta función)
Node:
elem.nodeType === 1
null:
variable === null
null o undefined:
variable == null
undefined:
Variables globales:
typeof variable === "undefined"
Variables locales:
variable === undefined
Propiedades:
object.prop === undefined
object.hasOwnProperty( prop )
"prop" in object
B. Conversiones implícitas de tipos
Considera lo que causaría lo siguiente...
Dado este HTML:
```html
<input type="text" id="foo-input" value="1">
```
```javascript
// 3.B.1.1
// `foo` ha sido declarado con el valor `0` y su tipo es `number`
var foo = 0;
// typeof foo;
// "number"
...
// En algún lugar, más tarde en tu código, necesitas modificar `foo`
// con un nuevo valor derivado del elemento input del HTML
foo = document.getElementById("foo-input").value;
// Si vas a testear `typeof foo` ahora, el resultado sería `string`
// Esto significa que si hubieras tenido lógica que comparar `foo` así:
if ( foo === 1 ) {
importantTask();
}
// `importantTask()` nunca habría sido evaluada, incluso con `foo` teniendo un valor de "1"
// 3.B.1.2
// Te puedes adelantar a los problemas, usando conversión de tipos con los operadores unarios + o - :
foo = +document.getElementById("foo-input").value;
// ^ el operador unario + va a convertir su operando derecho a number
// typeof foo;
// "number"
if ( foo === 1 ) {
importantTask();
}
// `importantTask()` va a ser llamada
```
Aquí hay algunos casos comunes de conversiones implícitas:
```javascript
// 3.B.2.1
var number = 1,
string = "1",
bool = false;
number;
// 1
number + "";
// "1"
string;
// "1"
+string;
// 1
+string++;
// 1
string;
// 2
bool;
// false
+bool;
// 0
bool + "";
// "false"
```
```javascript
// 3.B.2.2
var number = 1,
string = "1",
bool = true;
string === number;
// false
string === number + "";
// true
+string === number;
// true
bool === number;
// false
+bool === number;
// true
bool === string;
// false
bool === !!string;
// true
```
```javascript
// 3.B.2.3
var array = [ "a", "b", "c" ];
!!~array.indexOf( "a" );
// true
!!~array.indexOf( "b" );
// true
!!~array.indexOf( "c" );
// true
!!~array.indexOf( "d" );
// false
// Nótese que el ejemplo anterior debería ser considerado "innecesariamente inteligente"
// Prefiérase el método obvio de comparar el valor retornado de
// indexOf, como en:
if ( array.indexOf( "a" ) >= 0 ) {
// ...
}
```
```javascript
// 3.B.2.4
var num = 2.5;
parseInt( num, 10 );
// es lo mismo que...
~~num;
num >> 0;
num >>> 0;
// Todos resultan en 2
// Tener en cuenta que los números negativos serán tratados de otra manera...
var neg = -2.5;
parseInt( neg, 10 );
// es lo mismo que...
~~neg;
neg >> 0;
// Todos resultan en -2
// Sin embargo...
neg >>> 0;
// Va a resultar en 4294967294
```
4. <a name="cond">Evaluación condicional</a>
```javascript
// 4.1.1
// Cuando evaluamos para saber si un array tiene algún elemento,
// en lugar de hacer esto:
if ( array.length > 0 ) ...
// ...evaluar por el valor de verdad de la expresión, como en este caso:
if ( array.length ) ...
// 4.1.2
// Cuando solo evaluamos que un array está vacío,
// en lugar de esto:
if ( array.length === 0 ) ...
// ...evaluar el valor de verdad de la expresión:
if ( !array.length ) ...
// 4.1.3
// Cuando evaluamos que un string no es vacío,
// en vez de hacer esto:
if ( string !== "" ) ...
// ...evaluar el valor de verdad de la expresión:
if ( string ) ...
// 4.1.4
// Cuando evaluamos si un string es vacío,
// en lugar de:
if ( string === "" ) ...
// ...evaluar la expresión por falso, como aquí:
if ( !string ) ...
// 4.1.5
// Cuando evaluamos si una variable es true,
// en lugar de esto:
if ( foo === true ) ...
// ...expresar directamente de la siguiente manera:
if ( foo ) ...
// 4.1.6
// Cuando evaluamos si una variable es false,
// en vez de:
if ( foo === false ) ...
// ...usar negación y expresar de esta manera
if ( !foo ) ...
// ...Tener cuidado, porque la anterior expresión va a ser true también para: 0, "", null, undefined, NaN
// si se _DEBE_ testear por el valor false únicamente, utilizar el ===
if ( foo === false ) ...
// 4.1.7
// Cuando solamente se está evaluando una referencia que puede ser null o undefined, pero NO false, "" or 0,
// en lugar de:
if ( foo === null || foo === undefined ) ...
// ...tomar ventaja del uso del operador ==:
if ( foo == null ) ...
// Recuerda, usar == va a comparar `null` con AMBOS `null` y `undefined`
// pero no `false`, "" o 0
null == undefined
```
SIEMPRE evaluar por el mejor, por el resultado más preciso - lo de arriba es sólo una guía, no un dogma.
```javascript
// 4.2.1
// Sobre los tipos y evaluación de expresiones
Preferir `===` sobre `==` (a menos que el caso particular requiera una evaluación no fuertemente tipada)
=== no genera coerción de tipos, lo que significa que:
"1" === 1;
// false
== genera coerción de tipos, lo que significa que:
"1" == 1;
// true
// 4.2.2
// Booleanos, Verdaderos y Falsos
//Booleanos:
true, false
//Verdaderos:
"foo", 1
//Falsos:
"", 0, null, undefined, NaN, void 0
```
5. <a name="practical">Estilo práctico</a>
```javascript
// 5.1.1
// Un módulo práctico
(function( global ) {
var Module = (function() {
var data = "secret";
return {
// Esta es una propiedad booleana
bool: true,
// Algún valor string
string: "a string",
// Una propiedad Array
array: [ 1, 2, 3, 4 ],
// Una propiedad objeto
object: {
lang: "es-AR"
},
getData: function() {
// Obtener el valor de `data`
return data;
},
setData: function( value ) {
// asigna el valor de `data` y lo retorna
return ( data = value );
}
};
})();
// Otras cosas podrían pasar aquí
// Exponer nuestro módulo al módulo global
global.Module = Module;
})( this );
```
```javascript
// 5.2.1
// Un constructor práctico
(function( global ) {
function Ctor( foo ) {
this.foo = foo;
return this;
}
Ctor.prototype.getFoo = function() {
return this.foo;
};
Ctor.prototype.setFoo = function( val ) {
return ( this.foo = val );
};
// para llamar al constructor sin usar `new`, se podría hacer de la siguiente manera:
var ctor = function( foo ) {
return new Ctor( foo );
};
// Exponer nuestro constructor al objeto global
global.ctor = ctor;
})( this );
```
6. <a name="naming">Naming</a>
Si no eres un compilador/compresor humano de código, no te esfuerces por serlo.
A continuación ejemplos "tristes" de nombramiento de variables
```javascript
// 6.1.1
// Ejemplo de código con nombres de variables pobres / poco descriptivos
function q(s) {
return document.querySelectorAll(s);
}
var i,a=[],els=q("#foo");
for(i=0;i<els.length;i++){a.push(els[i]);}
```
Seguramente, alguna vez hayas escrito código como éste. Con un poco de suerte dejarás de hacerlo hoy mismo.
Aquí está el mismo fragmento, pero con un nombramiento de variables más inteligente (y una estructura más legible):
```javascript
// 6.A.2.1
// Ejemplo de código con nombres mejorados
function query( selector ) {
return document.querySelectorAll( selector );
}
var idx = 0,
elements = [],
matches = query("#foo"),
length = matches.length;
for( ; idx < length; idx++ ){
elements.push( matches[ idx ] );
}
```
Algunos tips más para nombramiento de variables:
```javascript
// 6.A.3.1
// Nombrando strings
`dog` es un string
// 6.A.3.2
// Nombrando arrays
`dogs` es un array de `dog` strings
// 6.A.3.3
// Nombrando funciones, objetos, instancias, etc.
camelCase; función y declaración de variable
// 6.A.3.4
// Nombrando constructores, prototypes, clases, etc.
PascalCase; función constructora
// 6.A.3.5
// Nombrando expresiones regulares
rDesc = //;
// 6.A.3.6
// Extraído de la guía de estilo de la Google Closure Library
functionNamesLikeThis;
variableNamesLikeThis;
ConstructorNamesLikeThis;
EnumNamesLikeThis;
methodNamesLikeThis;
SYMBOLIC_CONSTANTS_LIKE_THIS;
```
B. Caras de `this`
Mas allá de los generalmente bien conocidos casos de uso de `call` y `apply`, siempre preferir `.bind( this )` o equivalente, para crear definiciones de `BoundFunction` para invocar más tarde. Sólo recurrir a alias cuando no hay disponible una opción preferible.
```javascript
// 6.B.1
function Device( opts ) {
this.value = null;
// abre un stream async,
// esto va a ser llamado continuamente
stream.read( opts.path, function( data ) {
// Actualizar el valor de la instancia
// con el valor más reciente del
// data stream
this.value = data;
}.bind(this) );
// Regular la frecuencia de eventos emitidos de
// esta instancia de Device
setInterval(function() {
// Emitir un evento regulado
this.emit("event");
}.bind(this), opts.freq || 100 );
}
// Sólo hagamos de cuenta que heredamos de EventEmitter ;)
```
Cuando no esté disponible, equivalentes funcionales a `.bind` existen en muchas bibliotecas de JavaScript modernas.
```javascript
// 6.B.2
// ejemplo con lodash/underscore, _.bind()
function Device( 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 );
}
// ejemplo con jQuery.proxy
function Device( 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 );
}
// ejemplo con dojo.hitch
function Device( 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 );
}
```
Como última opción, crear un alias a `this` usando `self` como identificador. Esto es extremadamente sujeto a fallas y debería ser evitado cuando sea posible.
```javascript
// 6.B.3
function Device( opts ) {
var self = this;
this.value = null;
stream.read( opts.path, function( data ) {
self.value = data;
});
setInterval(function() {
self.emit("event");
}, opts.freq || 100 );
}
```
C. Usar `thisArg`
Varios prototype methods de ES 5.1 built-ins vienen con una firma especial `thisArg`, la cual debería ser usada cuando sea posible
```javascript
// 6.C.1
var obj;
obj = { f: "foo", b: "bar", q: "qux" };
Object.keys( obj ).forEach(function( key ) {
// |this| now refers to `obj`
console.log( this[ key ] );
}, obj ); // <-- el último argumento es `thisArg`
// Imprime...
// "foo"
// "bar"
// "qux"
```
`thisArg` puede ser usado con `Array.prototype.every`, `Array.prototype.forEach`, `Array.prototype.some`, `Array.prototype.map`, `Array.prototype.filter`
7. <a name="misc">Varios</a>
Esta sección servirá para describir ideas y conceptos que no deberían ser considerados dogmas, pero existen para alentar a cuestionarse prácticas, en un intento para encontrar mejores maneras de llevar a cabo tareas comunes de programación en JavaScript.
A. El uso de `switch` debería ser evitado, ya que los métodos modernos de tracing marcarán como negativas las funciones que contengan sentencias `switch`.
Parecen haber mejoras drásticas en la ejecución de sentencias `switch` en las últimas versiones de Firefox y Chrome.
http://jsperf.com/switch-vs-object-literal-vs-module
Mejoras destacables pueden ser vistas aquí también:
https://github.com/rwldrn/idiomatic.js/issues/13
```javascript
// 7.A.1.1
// Ejemplo de una sentencia switch
switch( foo ) {
case "alpha":
alpha();
break;
case "beta":
beta();
break;
default:
// hacer algo por defecto
break;
}
// 7.A.1.2
// Una manera alternativa que soporta componibilidad y reusabilidad es
// usar un objeto para guardar "cases" y una función para delegar:
var cases, delegator;
// returns de ejemplo sólo para demostración.
cases = {
alpha: function() {
// sentencias
// un return
return [ "Alpha", arguments.length ];
},
beta: function() {
// sentencias
// un return
return [ "Beta", arguments.length ];
},
_default: function() {
// sentencias
// un return
return [ "Default", arguments.length ];
}
};
delegator = function() {
var args, key, delegate;
// Transforma la lista de argumentos en un array
args = [].slice.call( arguments );
// Obtiene la llave del "case" del array
key = args.shift();
// Asigna el handler por defecto para el "case"
delegate = cases._default;
// Deriva el método a la operación delegada
if ( cases.hasOwnProperty( key ) ) {
delegate = cases[ key ];
}
// El argumento de alcance podría ser asignado a algo específico,
// en este caso, |null| va a ser suficiente
return delegate.apply( null, args );
};
// 7.A.1.3
// Poner la API de 7.A.1.2 a trabajar:
delegator( "alpha", 1, 2, 3, 4, 5 );
// [ "Alpha", 5 ]
// Por supuesto, el argumento de la llave del `case` podría ser
// basado en alguna otra condición arbitraria.
var caseKey, someUserInput;
// Possibly some kind of form input?
someUserInput = 9;
if ( someUserInput > 10 ) {
caseKey = "alpha";
} else {
caseKey = "beta";
}
// o...
caseKey = someUserInput > 10 ? "alpha" : "beta";
// Y luego...
delegator( caseKey, someUserInput );
// [ "Beta", 1 ]
// Y por supuesto...
delegator();
// [ "Default", 0 ]
```
B. Hacer un return temprano mejora la legibilidad del código y no tiene un impacto significativo en el rendimiento
```javascript
// 7.B.1.1
// Mal:
function returnLate( foo ) {
var ret;
if ( foo ) {
ret = "foo";
} else {
ret = "quux";
}
return ret;
}
// Bien:
function returnEarly( foo ) {
if ( foo ) {
return "foo";
}
return "quux";
}
```
8. <a name="native">Native & Host Objects</a>
El principio fundamental aquí es:
### No hagas cosas estúpidas y todo irá bien.
Para reforzar este concepto, mirar esta presentación:
#### “Everything is Permitted: Extending Built-ins” by Andrew Dupont (JSConf2011, Portland, Oregon) - recomendada!
[Andrew Dupont: Everything is Permitted: Extending Built-ins](https://www.youtube.com/watch?v=xL3xCO7CLNM)
9. <a name="comments">Comentarios</a>
#### Comentar en la línea que está justo arriba del código del que se está hablando
#### Comentarios en múltiples líneas son buenos
#### Comentarios en el fin de línea están prohibidos!
#### El estilo de JSDoc es bueno, pero requiere una inversión de tiempo significativa
10. <a name="language">Código en un lenguaje</a>
Los programas deberían ser escritos en un lenguaje, cualquiera sea, como sea impuesto por el mantenedor o mantenedores.
## Apéndice
### Coma Primero.
Cualquier proyecto que cite este documento como una guía para estilo no va a aceptar formateo de código con "coma primero", a menos que sea explícitamente especificado por el autor de ese proyecto.
----------
<a rel="license" href="https://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/3.0/80x15.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Principles of Writing Consistent, Idiomatic JavaScript</span> by <a xmlns:cc="https://creativecommons.org/ns#" href="https://github.com/rwldrn/idiomatic.js" property="cc:attributionName" rel="cc:attributionURL">Rick Waldron and Contributors</a> is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/rwldrn/idiomatic.js" rel="dct:source">github.com/rwldrn/idiomatic.js</a>.
================================================
FILE: translations/fr_FR/readme.md
================================================
# Principes d'écriture d'un code JavaScript cohérent et idiomatique
## Il s'agit d'un document vivant, les nouvelles idées pour améliorer le code autour de nous sont toujours les bienvenues. Pour contribuer : "fork", "clone", "branch", "commit", "push", "pull request".
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idangazit)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](http://www.opentutorials.org/course/167/1363) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Stephane Moreau [github](https://github.com/stmoreau)
* Boris Nekezov [github](https://github.com/boris-nekezov)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## Tout code, peu importe les bases sur lesquelles il est établi, devrait ressembler au code tapé par une seule personne, peu importe le nombre de personnes ayant contribué.
### La liste suivante donne un aperçu des pratiques que j'utilise dans tout le code dont je suis l'auteur. Les contributions aux projets dont je suis l'auteur doivent suivre ces lignes directrices.
### Je n'ai pas l'intention d'imposer mes préférences de style sur le code d'autres personnes. Si elles ont un style commun, dans ce cas, il est important de respecter le style de chacun.
> "Il est essentiel de réaliser que pour la réussite d'un projet, un bon intervenant ne doit pas coder pour soi-même mais pour les autres. Si un millier de personnes doivent utiliser votre code, écrivez-le avec un maximum de clarté, non pour des préférences personnelles, mais pour être au plus près du besoin." - Idan Gazit
## Traductions
* [ORIGINAL](https://github.com/rwldrn/idiomatic.js/)
* [Bulgarian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/bg_BG)
* [German](https://github.com/rwldrn/idiomatic.js/tree/master/translations/de_DE)
* [French](https://github.com/rwldrn/idiomatic.js/tree/master/translations/fr_FR)
* [Spanish](https://github.com/rwldrn/idiomatic.js/tree/master/translations/es_ES)
* [Portuguese - Brazil](https://github.com/rwldrn/idiomatic.js/tree/master/translations/pt_BR)
* [Korean](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ko_KR)
* [Japanese](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ja_JP)
* [Italian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/it_IT)
* [Russian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ru_RU)
* [Romanian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ro_RO)
* [简体中文](https://github.com/rwldrn/idiomatic.js/tree/master/translations/zh_CN)
* [Serbian - cyrilic alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ср_СР)
* [Serbian - latin aplphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/sr_SR)
* [Greek](https://github.com/rwaldron/idiomatic.js/tree/master/translations/gr_GR)
* [Hindi](https://github.com/rwaldron/idiomatic.js/tree/master/translations/hi_HI)
## Important, aspect non idiomatique :
### Qualité du Code : indispensables, ressources et références
* [JavaScript Plugin](http://docs.codehaus.org/display/SONAR/JavaScript+Plugin) for [Sonar](http://www.sonarsource.org/)
* [Plato](https://github.com/jsoverson/plato)
* [jsPerf](http://jsperf.com/)
* [jsFiddle](http://jsfiddle.net/)
* [jsbin](http://jsbin.com/)
* [JavaScript Lint (JSL)](http://javascriptlint.com/)
* [jshint](http://jshint.com/)
* [jslint](http://jslint.org/)
* [Editorconfig](http://editorconfig.org/)
[Optimisation des outils de qualité de code par Anton Kovalyov](http://anton.kovalyov.net/slides/gothamjs/)
### Soyez cohérent
[http://es5.github.com/](http://es5.github.com/)
Ce qui suit doit être considéré comme 1) __incomplet__, et comme une 2) __LECTURE OBLIGATOIRE__. Je ne suis pas toujours d'accord avec le style écrit par les auteurs ci-dessous, mais une chose est certaine : ils sont conformes. En outre, ce sont des autorités sur le langage.
* [Eloquent JavaScript](http://eloquentjavascript.net/)
* [JavaScript, JavaScript](http://javascriptweblog.wordpress.com/)
* [Rebecca Murphey](http://www.rebeccamurphey.com/) or [Adventures in JavaScript Development](http://rmurphey.com/)
* [Perfection Kills](http://perfectionkills.com/)
* [Douglas Crockford's Wrrrld Wide Web](http://www.crockford.com)
### Processus de "build" et de déploiement
Les projets doivent toujours tenter d'inclure des moyens de vérifier le code implémenté avec Lint, tester et minifier les fichiers afin d'avoir de meilleures performances en production.
Pour cette tâche, [Grunt](https://github.com/cowboy/grunt) maintenu par Ben Alman rassemble les bonnes pratiques, que nous soutenons dans notre projet.
### Testabilité
Les projets _doivent_ inclure certaines formes de test unitaire : tests d'implémentation et de périmètre fonctionnel. Utiliser des démos de cas d'utilisation NE SONT PAS des "tests". Ce qui suit est une liste de bibliothèques de test, aucune d'entre elles n'est approuvée plus que l'autre.
* [QUnit](http://github.com/jquery/qunit)
* [Jasmine](https://github.com/pivotal/jasmine)
* [Vows](https://github.com/cloudhead/vows)
* [Mocha](https://github.com/visionmedia/mocha)
* [Hiro](http://hirojs.com/)
* [JsTestDriver](https://code.google.com/p/js-test-driver/)
## Table des matières
* [Les Espaces](#whitespace)
* [Une Syntaxe Précise](#spacing)
* [Vérification de Type (Courtesy jQuery Core Style Guidelines)](#type)
* [Tests Conditionnels](#cond)
* [Style Pratique](#practical)
* [Règles de nommage](#naming)
* [Divers](#misc)
* [Native & Host Objects](#native)
* [Commentaires](#comments)
* [Un code, un langage](#language)
------------------------------------------------
## Préface
Les sections suivantes décrivent un guide de style _raisonable_ pour tout développement moderne en JavaScript et ne sont pas censées être normatives. Le plus important à appliquer est la **loi de cohérence dans le style de code**. Le style que vous avez choisi pour votre projet, quel qu'il soit, doit être considéré comme la loi. Référer à ce document pour afficher l'engagement de votre projet à utiliser un style de code cohérent, lisible et maintenable.
## Manifeste : style idiomatique
1. <a name="whitespace">Les Espaces</a>
- Ne jamais mélanger les espaces et les tabulations.
- Avant d'écrire le moindre code en début de projet, vous devez choisir entre l'indentation par espace ou par tabulation. C'est une règle.
- Pour la lisibilité, paramétrez votre éditeur avec une indentation de deux caractères — ce qui veut dire deux espaces ou une tabulation représentant deux espaces.
- Si votre éditeur le supporte, travaillez toujours avec le mode "afficher les caractères invisibles" actif. Les avantages de cette pratique sont :
- Améliorer la cohérence du code
- Éliminer les espaces de fin de ligne
- Éliminer les espaces utilisées pour des lignes blanches
- Améliorer la lisibilité de vos "commit" et des "diff"
2. <a name="spacing">Une Syntaxe Précise</a>
A. Parenthèses, Accolades, Sauts de ligne
```javascript
// if/else/for/while/try ont toujours des espaces, des parenthèses et plusieurs sauts de ligne
// cela améliore la lisibilité
// 2.A.1.1
// Exemples de mauvaises pratiques
if(condition) doSomething();
while(condition) iterating++;
for(var i=0;i<100;i++) someIterativeFn();
// 2.A.1.1
// Utilisez les espaces afin d'améliorer la lisibilité
if ( condition ) {
// déclarations
}
while ( condition ) {
// déclarations
}
for ( var i = 0; i < 100; i++ ) {
// déclarations
}
// même mieux :
var i,
length = 100;
for ( i = 0; i < length; i++ ) {
// déclarations
}
// Ou...
var i = 0,
length = 100;
for ( ; i < length; i++ ) {
// déclarations
}
var prop;
for ( prop in object ) {
// déclarations
}
if ( true ) {
// déclarations
} else {
// déclarations
}
```
B. Déclaration, Affectation, Fonction ( Nommage, Expression, Constructeur )
```javascript
// 2.B.1.1
// Variables
var foo = "bar",
num = 1,
undef;
// Notations littérales :
var array = [],
object = {};
// 2.B.1.2
// Utiliser une unique déclaration `var` par portée de (fonction) améliore la
// lisibilité et permet de garder une déclaration séparée du corps de la fonction
// (en adéquation avec la portée des variables JS)
// Mauvais
var foo = "";
var bar = "";
var qux;
// Correct
var foo = "",
bar = "",
quux;
// ou..
var // donnez votre avis
foo = "",
bar = "",
quux;
// 2.B.1.3
// La déclaration des variables 'var' doit toujours être au début de la portée de chaque fonction.
// Le même principe s'applique au 'const' défini dans ECMAScript 6.
// Mauvais
function foo() {
// déclarations
var bar = "",
qux;
}
// Correcte
function foo() {
var bar = "",
qux;
// toutes les autres déclarations sont après la déclaration des variables.
}
```
```javascript
// 2.B.2.1
// Déclaration de fonction nommée
function foo( arg1, argN ) {
}
// Utilisation
foo( arg1, argN );
// 2.B.2.2
// Déclaration de fonction nommée
function square( number ) {
return number * number;
}
// Utilisation
square( 10 );
// Passage d'une callback par variable nommée
function square( number, callback ) {
callback( number * number );
}
square( 10, function( square ) {
// déclaration de la callback
});
// 2.B.2.3
// Expression de fonction
var square = function( number ) {
// Renvoie quelque chose de pertinent
return number * number;
};
// Expression de fonction avec un identifiant
// Cette forme préférée a pour valeur ajoutée d'être en mesure de se faire appeler
// et d'avoir une identité dans les traces de pile
var factorial = function factorial( number ) {
if ( number < 2 ) {
return 1;
}
return number * factorial( number-1 );
};
// 2.B.2.4
// Déclaration de Constructeur
function FooBar( options ) {
this.options = options;
}
// Utilisation
var fooBar = new FooBar({ a: "alpha" });
fooBar.options;
// { a: "alpha" }
```
C. Exceptions et légères différences
```javascript
// 2.C.1.1
// Fonctions avec 'callbacks'
foo(function() {
// remarque : il n'y a pas d'espace supplémentaire entre la première parenthèse
// d'exécution de la fonction appelée et le mot réservé "function"
});
// Fonction acceptant un tableau, sans espace
foo([ "alpha", "beta" ]);
// 2.C.1.2
// Fonction acceptant un objet, sans espace
foo({
a: "alpha",
b: "beta"
});
// Regroupement de déclaration à l'intérieur de parenthèse, sans espace
if ( !("foo" in obj) ) {
}
```
D. La cohérence gagne toujours
Dans les sections 2.A-2.C, les règles d'espacement sont énoncées sous forme de recommandation avec un objectif simple et plus abouti : la cohérence.
Il est important de noter que les préférences de formatage, telles que les "espaces situées à l'intérieur de déclaration", doivent être considérées comme optionnelles. Un _unique style_ doit exister pour toutes les sources d'un projet.
```javascript
// 2.D.1.1
if (condition) {
// déclarations
}
while (condition) {
// déclarations
}
for (var i = 0; i < 100; i++) {
// déclarations
}
if (true) {
// déclarations
} else {
// déclarations
}
```
E. Fin de ligne et lignes vides
Les espaces peuvent anéantir la lisibilité de vos "diffs". Considérez que la suppression des espaces et des espaces en fin de ligne doit être effectuée __automatiquement__ avant chaque "commit".
3. <a name="type">Vérification de Type (Courtesy jQuery Core Style Guidelines)</a>
3.A Types réels
* String :
`typeof variable === "string"`
* Number :
`typeof variable === "number"`
* Boolean :
`typeof variable === "boolean"`
* Object :
`typeof variable === "object"`
* Array :
`Array.isArray(arrayObject)`
(dans la mesure du possible)
* null :
`variable === null`
* null ou undefined :
`variable == null`
* undefined :
* Variable globale :
* `typeof variable === "undefined"`
* Variable locale :
* `variable === undefined`
* Propriétés :
* `object.prop === undefined`
* `object.hasOwnProperty( prop )`
* `"prop" in object`
JavaScript est un langage typé dynamiquement - ce qui peut être votre meilleur ami comme votre pire ennemi : respectez donc les 'types', en appliquant les règles ci-dessus.
3.B Conversion de type
Considérons les implications de ce qui suit...
Etant donné ce code HTML :
```html
<input type="text" id="foo-input" value="1">
```
```js
// 3.B.1.1
// `foo` a été déclaré avec la valeur `0` et son type est `number`
var foo = 0;
// typeof foo;
// "number"
...
// Quelque part plus loin dans votre code, vous devez mettre
jour `foo`
// avec une nouvelle valeur issue de l'élément 'input'
foo = document.getElementById("foo-input").value;
// Si vous deviez tester `typeof foo` maintenant, le résultat serait "string"
// Cela signifie que si vous aviez la logique testant `foo` comme suit :
if ( foo === 1 ) {
important();
}
// `important()` ne serait jamais évalué, même si `foo` a une valeur de "1"
// 3.B.1.2
// Vous pouvez vous prémunir de ce problème en utilisant la conversion de type avec l'opérateur unaire + ou - :
foo = +document.getElementById("foo-input").value;
^ opérateur unaire + convertissant à sa droite l'opérande en "number"
// typeof foo;
// "number"
if ( foo === 1 ) {
important();
}
// `important()` sera évalué
```
Voici quelques cas courants de conversion :
```javascript
// 3.B.2.1
var number = 1,
string = "1",
bool = false;
number;
// 1
number + "";
// "1"
string;
// "1"
+string;
// 1
+string++;
// 1
string;
// 2
bool;
// false
+bool;
// 0
bool + "";
// "false"
```
```javascript
// 3.B.2.2
var number = 1,
string = "1",
bool = true;
string === number;
// false
string === number + "";
// true
+string === number;
// true
bool === number;
// false
+bool === number;
// true
bool === string;
// false
bool === !!string;
// true
```
```javascript
// 3.B.2.3
var array = [ "a", "b", "c" ];
!!~array.indexOf( "a" );
// true
!!~array.indexOf( "b" );
// true
!!~array.indexOf( "c" );
// true
!!~array.indexOf( "d" );
// false
var num = 2.5;
parseInt( num, 10 );
// identique à...
~~num;
```
4. <a name="cond">Tests Conditionnels</a>
```javascript
// 4.1.1
// Lorsque vous évaluez que la taille d'un tableau est non nulle,
// Plutôt que d'utiliser l'expression suivante :
if ( array.length > 0 ) ...
// ...préférez :
if ( array.length ) ...
// 4.1.2
// A l'inverse, lorsque vous évaluez si un tableau est vide,
// Plutôt que d'utiliser l'expression suivante :
if ( array.length === 0 ) ...
// ...préférez :
if ( !array.length ) ...
// 4.1.3
// Lorsque vous évaluez si une chaîne est non vide,
// Plutôt que d'utiliser l'expression suivante :
if ( string !== "" ) ...
// ...préférez :
if ( string ) ...
// 4.1.4
// A l'inverse, lorsque vous évaluez si une chaîne est vide,
// Plutôt que d'utiliser l'expression suivante :
if ( string === "" ) ...
// ...préférez :
if ( !string ) ...
// 4.1.5
// Lorsque vous évaluez si une référence est vraie,
// Plutôt que d'utiliser l'expression suivante :
if ( foo === true ) ...
// ...évaluez ce que cela signifie et bénéficiez des tests primitifs :
if ( foo ) ...
// 4.1.6
// Lorsque vous évaluez si une référence est fausse,
// Plutôt que d'utiliser l'expression suivante :
if ( foo === false ) ...
// ...utilisez la négation et la conversion de l'évaluation de la vérité :
if ( !foo ) ...
// ...Soyez prudent, cela correspondra aux valeurs suivantes : 0, "", null, undefined, NaN
// Vous _DEVEZ_ dans ce cas tester la valeur `faux`, comme suit :
if ( foo === false ) ...
// 4.1.7
// Lorsque vous évaluez une référence et seulement une référence qui peut être null ou undefined, mais NOT fausse, "" ou 0,
// Plutôt que d'utiliser l'expression suivante :
if ( foo === null || foo === undefined ) ...
// ...bénéficiez de la conversion de type ==, comme suit :
if ( foo == null ) ...
// Souvenez-vous, utiliser == vérifiera une égalité avec `null` et `null` & `undefined`
// mais pas `false`, "" ou 0
null == undefined
```
_TOUJOURS_ tester avec le meilleur et le plus performant des résultats - les consignes ci-dessus sont une ligne de conduite et non un dogme.
```javascript
// 4.2.1
// Conversion de type et remarques
Preferez `===` à la place de `==` (à moins que le cas de test ne requiert la perte d'évaluation de type)
=== n'effectue pas de conversion de type, ce qui signifie que :
"1" === 1;
// faux
== effectue la conversion de type, ce qui signifie que :
"1" == 1;
// vrai
// 4.2.2
// Booléens, valeurs de vérité et de négation
Booléens : true, false
sont vrais : "foo", 1
sont faux : "", 0, null, undefined, NaN, void 0
```
5. <a name="practical">Style usuel</a>
```javascript
// 5.1.1
// Module
(function( global ) {
var Module = (function() {
var data = "secret";
return {
//Ceci est une proprété booléenne (boolean)
bool: true,
// Une chaîne de caractère (string)
string: "a string",
// Une propriété tableau (array)
array: [ 1, 2, 3, 4 ],
// Une propriété objet (object)
object: {
lang: "en-Us"
},
getData: function() {
// obtenir la valeur courante de `data`
return data;
},
setData: function( value ) {
// affecter une valeur `value` à `data` et la renvoyer
return ( data = value );
}
};
})();
// D'autres choses peuvent être implémentées ici
// Exposition de notre module via l'objet global
global.Module = Module;
})( this );
```
```javascript
// 5.2.1
// Constructeur
(function( global ) {
function Ctor( foo ) {
this.foo = foo;
return this;
}
Ctor.prototype.getFoo = function() {
return this.foo;
};
Ctor.prototype.setFoo = function( val ) {
return ( this.foo = val );
};
// Appel du contructeur sans `new`, en utilisant cette syntaxe :
var ctor = function( foo ) {
return new Ctor( foo );
};
// Exposition de notre constructeur via l'objet global
global.ctor = ctor;
})( this );
```
6. <a name="naming">Règles de nommage</a>
Vous n'êtes pas un compilateur ou un minificateur, il ne faut pas essayer d'en être un.
Le code suivant est un exemple flagrant de ce qu'il ne faut pas faire :
```javascript
// 6.1.1
// Example of code with poor names
function q(s) {
return document.querySelectorAll(s);
}
var i,a=[],els=q("#foo");
for(i=0;i<els.length;i++){a.push(els[i]);}
```
Vous avez peut-être déjà écrit un code comme ci-dessus - nous espérons que cette mauvaise pratique se terminera aujourd'hui.
Ci-dessous la même logique, avec plus de clarté et surtout plus de lisibilité fonctionnelle :
```javascript
// 6.2.1
// Exemple de code avec un nommage amélioré
function query( selector ) {
return document.querySelectorAll( selector );
}
var idx = 0,
elements = [],
matches = query("#foo"),
length = matches.length;
for( ; idx < length; idx++ ){
elements.push( matches[ idx ] );
}
```
Quelques conseils supplémentaires :
```javascript
// 6.3.1
// Nommage des chaînes de caractères "string"
`dog` est une chaîne de caractère
// 6.3.2
// Nommage des chaînes des tableaux "array"
`dogs` est un tableau de `dog` chaîne de caractère
// 6.3.3
// Nommage des fonctions, objets, instances, etc
camelCase; fonction et déclarations var
// 6.3.4
// Nommage des contructeurs, prototypes, etc.
PascalCase; fonction constructeur
// 6.3.5
// Nommage des expressions régulières
rDesc = //;
// 6.3.6
// Extrait du guide de la librairie de Google Closure
functionNamesLikeThis;
variableNamesLikeThis;
ConstructorNamesLikeThis;
EnumNamesLikeThis;
methodNamesLikeThis;
SYMBOLIC_CONSTANTS_LIKE_THIS;
```
7. <a name="misc">Divers</a>
Cette section servira à illustrer des idées et des concepts qui ne devraient pas être considérés comme un dogme, mais il existe, au lieu d'encourager les pratiques en doute dans une tentative de trouver de meilleures façons de le faire les tâches courantes de programmation JavaScript.
A. L'utilisation des `switch` doit être évitée, les méthodes modernes de tracking devraient 'blacklister' l'utilisation des fonctions avec `switch`.
Il semble y avoir des améliorations radicales à l'exécution des déclarations de `switch` dans les dernières version de Firefox et Chrome.
http://jsperf.com/switch-vs-object-literal-vs-module
Des améliorations notables sont également visibles ici :
https://github.com/rwldrn/idiomatic.js/issues/13
```javascript
// 7.A.1.1
// Exemple de déclaration de `switch`
switch( foo ) {
case "alpha":
alpha();
break;
case "beta":
beta();
break;
default:
// comportement par défaut
break;
}
// 7.A.1.2
// Une meilleure approche est d'utiliser un object littéral ou même un module :
var switchObj = {
alpha: function() {
// déclarations
// return
},
beta: function() {
// déclarations
// return
},
_default: function() {
// déclarations
// return
}
};
var switchModule = (function () {
return {
alpha: function() {
// déclarations
// return
},
beta: function() {
// déclarations
// return
},
_default: function() {
// déclarations
// return
}
};
})();
// 7.A.1.3
// If `foo` is a property of `switchObj` or `switchModule`, execute as a method...
( Object.hasOwnProperty.call( switchObj, foo ) && switchObj[ foo ] || switchObj._default )( args );
( Object.hasOwnProperty.call( switchObj, foo ) && switchModule[ foo ] || switchModule._default )( args );
// If you know and trust the value of `foo`, you could even omit the OR check
// leaving only the execution:
switchObj[ foo ]( args );
switchModule[ foo ]( args );
// This pattern also promotes code reusability.
```
B. Les "return" prématurés permettent d'améliorer la lisibilité du code avec une différence de performance négligeable
```javascript
// 7.B.1.1
// Bad:
function returnLate( foo ) {
var ret;
if ( foo ) {
ret = "foo";
} else {
ret = "quux";
}
return ret;
}
// Good:
function returnEarly( foo ) {
if ( foo ) {
return "foo";
}
return "quux";
}
```
8. <a name="native">Native & Host Objects</a>
Le principe de base est ici :
### Ne faites pas de choses stupides et tout sera OK.
Pour renforcer ce concept, regardez s'il vous plaît la présentation suivante :
#### “Everything is Permitted: Extending Built-ins” by Andrew Dupont (JSConf2011, Portland, Oregon)
https://www.youtube.com/watch?v=xL3xCO7CLNM
9. <a name="comments">Commentaires</a>
* Le style de commentaire JSDoc est bon (Closure Compiler type hints++)
* Une seule ligne de commentaire au-dessus du code auquel il s'applique
* L'utilisation de plusieurs lignes est bonne
* Les commentaires en fin de ligne sont interdits !
10. <a name="language">Un code, un langage</a>
Les programmes doivent être rédigés dans un langage, quel que soit le langage, le mainteneur ou les mainteneurs doivent donner les bonnes pratiques.
## Appendice
### Première virgule.
Tout projet qui cite ce document comme son guide de style de base ne pourra accepter le formatage du code première virgule, sauf mention contraire.
================================================
FILE: translations/gr_GR/readme.md
================================================
# Αρχές γραφής συνεπούς και ιδιοματικής Javascript
## Αυτό είναι απλά ένα αρχείο και νέες ιδέες που βελτιώνουν τον κώδικα γύρω μας είναι πάντα ευπρόσδεκτες. Συνεισφέρετε, κάντε fork, clone, branch, commit, push και pull request.
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idan)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](http://www.opentutorials.org/course/167/1363) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Firede [@firede](https://twitter.com/firede) [github](https://github.com/firede)
* monkadd [github](https://github.com/monkadd)
* Stephan Lindauer [@stephanlindauer](http://twitter.com/stephanlindauer), [github](https://github.com/stephanlindauer)
* Thomas P [@dragon5689](https://twitter.com/dragon5689) [github](https://github.com/dragon5689)
* Yotam Ofek [@yotamofek](https://twitter.com/yotamofek) [github](https://github.com/yotamofek)
* Aleksandr Filatov [@greybax](http://twitter.com/greybax), [github](https://github.com/greybax)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Hao-Wei Jeng [@l0ckys](http://twitter.com/l0ckys), [github](https://github.com/lockys)
* Richard Gibson [@gibson042](http://twitter.com/gibson042), [github](https://github.com/gibson042)
* Fesuy [github](https://github.com/fesuydev)
* Stephane Moreau [github](https://github.com/stmoreau)
* Boris Nekezov [github](https://github.com/boris-nekezov)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## Όλος ο κώδικας σε ένα project πρέπει να φαίνεται σαν να τον έχει γράψει ένα άτομο, ασχέτως του πόσα άτομα έχουν συνεισφέρει.
### Η παρακάτω λίστα δείχνει τις πρακτικές που ακολουθώ σε όλον τον κώδικα για τον οποίο είμαι ο author. Contributions σε projects που έχω δημιουργήσει πρέπει να ακολουθούν αυτές τις οδηγίες.
### Δεν σκοπεύω να επιβάλω τα style preferences μου σε κώδικα άλλων ανθρώπων, αν ένα κοινό στυλ υπάρχει πρέπει να ακολουθείται αυτό.
> ### "Επιχειρήματα αντί για στυλ δεν έχει νόημα. Θα πρέπει να υπάρχει ένα style guide και θα πρέπει να το ακολουθείτε"
>_Rebecca_ _Murphey_
> ### "Μέρος του να είσαι καλός διαχειριστής ενός επιτυχημένου project είναι η συνειδητοποίηση ότι το να γράφεις κώδικα για τον εαυτό σου είναι κακή ιδέα. Εάν χιλιάδες άνθρωποι χρησιμοποιούν τον κωδικό σας, τότε γράψτε τον κωδικό σας για μέγιστη σαφήνεια, όχι με την προσωπική σας προτίμηση για το πώς να το παίξετε έξυπνοι με το spec."
>_Idan_ _Gazit_
## Translations
* [ORIGINAL](https://github.com/rwldrn/idiomatic.js/)
* [Bulgarian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/bg_BG)
* [German](https://github.com/rwldrn/idiomatic.js/tree/master/translations/de_DE)
* [French](https://github.com/rwldrn/idiomatic.js/tree/master/translations/fr_FR)
* [Spanish](https://github.com/rwldrn/idiomatic.js/tree/master/translations/es_ES)
* [Portuguese - Brazil](https://github.com/rwldrn/idiomatic.js/tree/master/translations/pt_BR)
* [Korean](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ko_KR)
* [日本語](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ja_JP)
* [Italian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/it_IT)
* [Russian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ru_RU)
* [Romanian](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ro_RO)
* [简体中文](https://github.com/rwldrn/idiomatic.js/tree/master/translations/zh_CN)
* [Serbian - cyrilic alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/ср_СР)
* [Serbian - latin alphabet](https://github.com/rwldrn/idiomatic.js/tree/master/translations/sr_SR)
* [繁體中文](https://github.com/rwaldron/idiomatic.js/tree/master/translations/zh_TW)
* [Indonesian](https://github.com/rwaldron/idiomatic.js/tree/master/translations/id_ID)
* [Greek](https://github.com/rwaldron/idiomatic.js/tree/master/translations/gr_GR)
* [Hindi](https://github.com/rwaldron/idiomatic.js/tree/master/translations/hi_HI)
## Σημαντικά, Μη-Ιδιωματικά Πράγματα:
### Code Quality Εργαλεία, Πόροι & Αναφορές
* [JavaScript Plugin](http://docs.codehaus.org/display/SONAR/JavaScript+Plugin) για το [Sonar](http://www.sonarsource.org/)
* [Plato](https://github.com/es-analysis/plato)
* [jsPerf](http://jsperf.com/)
* [jsFiddle](http://jsfiddle.net/)
* [Codepen](http://codepen.io/)
* [jsbin](http://jsbin.com/)
* [JavaScript Lint (JSL)](http://javascriptlint.com/)
* [jshint](http://jshint.com/)
* [jslint](http://jslint.org/)
* [eslint](http://eslint.org/)
* [jscs](https://www.npmjs.org/package/jscs)
* [jscodesniffer](https://www.npmjs.org/package/jscodesniffer)
* [Editorconfig](http://editorconfig.org/)
* [Hound](https://houndci.com/)
## Γίνετε έξυπνοι
### [Annotated ECMAScript 5.1](http://es5.github.com/)
### [EcmaScript Language Specification, 5.1 Edition](http://ecma-international.org/ecma-262/5.1/)
Τα επόμενα θα πρέπει να θεωρρηθούν 1) μη τελειωμένα και 2) *ΑΠΑΡΑΙΤΗΤΟ ΔΙΑΒΑΣΜΑ*. Δεν συμφωνώ πάντα με το στυλ που χρησιμοποιείται από τους παρακάτω συγγραφείς, αλλά ένα είναι σίγουρο: είναι συνεπής. Επιπλέον, πρόκειται για αρχές σχετικά με τη γλώσσα.
* [Baseline For Front End Developers: 2015](http://rmurphey.com/blog/2015/03/23/a-baseline-for-front-end-developers-2015/)
* [Eloquent JavaScript](http://eloquentjavascript.net/)
* [JavaScript, JavaScript](http://javascriptweblog.wordpress.com/)
* [Adventures in JavaScript Development](http://rmurphey.com/)
* [Perfection Kills](http://perfectionkills.com/)
* [Douglas Crockford's Wrrrld Wide Web](http://www.crockford.com)
* [JS Assessment](https://github.com/rmurphey/js-assessment)
### Διαδικασία Δημιουργίας και Deployment
Τα project θα πρέπει πάντα να προσπαθούν να περιέχουν κάποιους γενικούς τρόπους με τους οποίους να μπορούν να γίνουν linted, tested και συμπιεσμένα για την παραγωγή. Για αυτή τη διαδικασία το [grunt](https://github.com/gruntjs/grunt) από τον Ben Alman και το [webpack](https://github.com/webpack/webpack) είναι σπουδαία εργαλεία.
### Test Facility
Τα projects _πρέπει_ να περιέχουν κάποιου είδους unit, reference, implementation ή functional testing. Παρακάτω είναι μια λίστα με test frameworks, εκ των οποίων κανένα δεν συνιστάται πιο πολύ από τα άλλα.
* [QUnit](http://github.com/jquery/qunit)
* [Jasmine](https://github.com/pivotal/jasmine)
* [Vows](https://github.com/cloudhead/vows)
* [Mocha](https://github.com/visionmedia/mocha)
* [Hiro](http://hirojs.com/)
* [JsTestDriver](https://code.google.com/p/js-test-driver/)
* [Buster.js](http://busterjs.org/)
* [Sinon.js](http://sinonjs.org/)
* [Tape](https://github.com/substack/tape)
## Πίνακας περιεχομένων
* [Λευκός χώρος](#whitespace)
* [Όμορφο Συντακτικό](#spacing)
* [Έλεγχος τύπου (ευγενείς οδηγίες jQuery Core Style)](#type)
* [Conditional Evaluation](#cond)
* [Πρακτικό στυλ](#practical)
* [Ονομασία](#naming)
* [Διάφορα](#misc)
* [Native & Host Objects](#native)
* [Σχόλια](#comments)
* [Ένας κώδικας γλώσσας](#language)
------------------------------------------------
## Πρόλογος
Τα επόμενα τμήματα δείχνουν ένα _λογικό_ style guide για μοντέρνο JavaScript development και δεν είναι εντεταλμένα. Το πιο σημαντικό στοιχείο να αποκομίσετε είναι ο **νόμος της code style συνέπειας**. Ό,τι και να διαλέξετε για το στυλ του project σας πρέπει λαμβάνεται ως νόμος.
## Ιδιωματικό Style Manifesto
1. <a name="whitespace">Λευκός χώρος</a>
- Ποτέ να μην συνδιάζετε κενά και tabs.
- Όταν ξεκινάτε ένα project, πριν γράψετε καν κώδικα, διαλέξτε ανάμεσα σε κενά ή tabs και θεωρήστε το **νόμο**.
- Για να είναι ευανάγνωστο, πάντα προτείνω να σετάρετε το indent του editor σας σε 2 χαρακτήρες — αυτό σημαίνει πως δυο κενά αντιπροσωπεύουν ένα tab.
- Αν το υποστηρίζει ο editor σας, πάντα να δουλεύετε με το "show invisibles" αναμένο. Τα πλεονεκτήματα αυτού είναι:
- Ενισχυμένη συνοχή
- Εξάλειψη των κενών στο τέλος της γραμμής
- Εξάλειψη των κενών γραμμών
- Commits και diffs που είναι ευκολότερα να διαβαστούν
- Χρησιμοποιείτε [Editorconfig](http://editorconfig.org/) όποτε μπορείτε. Υποστηρίζει τα περισσότερα IDEs και διαχειρίζεται τις πεισσότερες ρυθμίσεις για τους κενούς χώρους.
2. <a name="spacing">Όμορφο Συντακτικό</a>
A. Parens, Braces, Linebreaks
```javascript
// if/else/for/while/try πάντα έχουν κενά, braces and span πολλαπλές γραμμές
// προωθεί το readability
// 2.A.1.1
// παραδείγματα από πραγματικά πυκνό συντακτικό
if(condition) doSomething();
while(condition) iterating++;
for(var i=0;i<100;i++) someIterativeFn();
// 2.A.1.1
// Χρησιμοποιείστε τα κενά για να προωθήσετε το readability
if ( condition ) {
// statements
}
while ( condition ) {
// statements
}
for ( var i = 0; i < 100; i++ ) {
// statements
}
// Ακόμα καλύτερα:
var i,
length = 100;
for ( i = 0; i < length; i++ ) {
// statements
}
// Or...
var i = 0,
length = 100;
for ( ; i < length; i++ ) {
// statements
}
var prop;
for ( prop in object ) {
// statements
}
if ( true ) {
// statements
} else {
// statements
}
```
B. Assignments, Declarations, Functions ( Named, Expression, Constructor )
```javascript
// 2.B.1.1
// Variables
var foo = "bar",
num = 1,
undef;
// Literal notations:
var array = [],
object = {};
// 2.B.1.2
// Χρησιμοποιώντας ένα `var` ανά scope (function) ή ένα `var` για κάθε μεταβλητή,
// προωθείτε το readability και κρατιέται το declaration list χωρίς ακαταστασία.
// Χρησιμοποιώντας ένα `var` ανά μεταβλητή έχετε καλύτερο έλεγχο των versions
// και κάνει ευκολότερο να μετακινείτε τις γραμμές.
// Ένα `var` ανά scope κάνει ευκολότερο το να βρίσκετε undeclared variables
// που μπορεί να γίνουν implied globals.
// Διαλέξτε καλύτερα για το project σας και ποτέ μην τα αναμιγνύετε.
// Κακό
var foo = "",
bar = "";
var qux;
// Καλό
var foo = "";
var bar = "";
var qux;
// ή αλλιώς..
var foo = "",
bar = "",
qux;
// ή..
var // Comment σε αυτά
foo = "",
bar = "",
quux;
// 2.B.1.3
// var statements πρέπει να είναι πάντα στην αρχή του respective scope (function).
// κακό
function foo() {
// some statements here
var bar = "",
qux;
}
// καλό
function foo() {
var bar = "",
qux;
// all statements after the variables declarations.
}
// 2.B.1.4
// const και let, από το ECMAScript 6, πρέπει να είναι στην αρχή του scope (block) τους.
// κακό
function foo() {
let foo,
bar;
if ( condition ) {
bar = "";
// statements
}
}
// καλό
function foo() {
let foo;
if ( condition ) {
let bar = "";
// statements
}
}
```
```javascript
// 2.B.2.1
// Named Function Declaration
function foo( arg1, argN ) {
}
// Χρήση
foo( arg1, argN );
// 2.B.2.2
// Named Function Declaration
function square( number ) {
return number * number;
}
// Χρήση
square( 10 );
// Really contrived continuation passing style
function square( number, callback ) {
callback( number * number );
}
square( 10, function( square ) {
// callback statements
});
// 2.B.2.3
// Function Expression
var square = function( number ) {
// Return something valuable and relevant
return number * number;
};
// Function Expression with Identifier
// Αυτή η χρήση έχει το πλεονέκτημα ότι μπορεί να καλεσθέι
// από τον εαυτό της και έχει ένα identity στα stack traces:
var factorial = function factorial( number ) {
if ( number < 2 ) {
return 1;
}
return number * factorial( number - 1 );
};
// 2.B.2.4
// Constructor Declaration
function FooBar( options ) {
this.options = options;
}
// Χρήση
var fooBar = new FooBar({ a: "alpha" });
fooBar.options;
// { a: "alpha" }
```
C. Εξαιρέσεις, ελαφρές αποκλίσεις
```javascript
// 2.C.1.1
// Functions with callbacks
foo(function() {
// Προσέξτε ότι δεν υπάρχει έξτρα κενό ανάμεσα στο πρώτο paren
// του executing function call και της λέξης "function"
});
// Function δεχόμενο ένα array, όχι κενό
foo([ "alpha", "beta" ]);
// 2.C.1.2
// Function δεχόμενο ένα object, όχι κενό
foo({
a: "alpha",
b: "beta"
});
// Single argument string literal, όχι κενό
foo("bar");
// Expression parens, όχι κενό
if ( !("foo" in obj) ) {
obj = (obj.bar || defaults).baz;
}
```
D. Η συνέπεια πάντα κερδίζει
Στα κεφάλαια 2.A-2.C, οι κανόνες των κενών ορίζονται ως σύσταση με έναν απλούστερο, ψηλότερο σκοπό: η συνέπεια.
Είναι σημαντικό να σημειώσουμε πως τα formatting preferences, όπως το "inner whitespace" πρέπει να θεωρούνται προαιρετικά, αλλά ένα στυλ πρέπει να υπάρχει σε όλο το project σας.
```javascript
// 2.D.1.1
if (condition) {
// statements
}
while (condition) {
// statements
}
for (var i = 0; i < 100; i++) {
// statements
}
if (true) {
// statements
} else {
// statements
}
```
E. Quotes
Είτε προτιμάτε μονά ή διπλά δεν πειράζειμ δεν υπάρχει διαφορά στο πως η Javascript τα διαβάζει. Αυτό που **ΟΠΩΣ ΚΑΙ ΔΗΠΟΤΕ ΠΡΕΠΕΙ** να ενισχυθεί είναι η συνέπεια. **Ποτέ μην χρησιμοποιείτε και τα δυο στο ίδιο project. Διαλέξτε ένα στυλ και ακολουθείστε αυτο.**
F. Τέλος γραμμών και κενές γραμμές
Το κενό μπορεί να καταστρέψει τα diffs και να τα κάνει αδύνατο να διαβαστούν. Σκεφτείτε να συμπεριλαμβάνετε ένα pre-commit hook που θα διαγράφει το end-of-line κενό και τα blanks spaces στις κενές γραμμές αυτόματα.
3. <a name="type">Έλεγχος τύπου (ευγενείς οδηγίες jQuery Core Style)</a>
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
Σκεφτείτε τις εφαρμογές των παρακάτω...
Έχοντας αυτό το HTML:
```html
<input type="text" id="foo-input" value="1">
```
```javascript
// 3.B.1.1
// `foo` έχει γίνει declared με την τιμή `0` και ο τύπος είναι `number`
var foo = 0;
// typeof foo;
// "number"
...
// Κάπου αργότερα στον κώδικα, πρέπει να ανανεώσετε το `foo`
// με μία καινούρια τιμή από ένα input element
foo = document.getElementById("foo-input").value;
// Άμα θέλατε να τεστάρετε `typeof foo` τώρα, το αποτέλεσμα θα ήταν `string`
// Αυτό σημαίνει πως αν είχατε λογική που να τεστάρει το `foo`:
if ( foo === 1 ) {
importantTask();
}
// `importantTask()` δεν θα γινόταν ποτέ evaluated, ακόμα και αν το `foo` έχει την τιμή "1"
// 3.B.1.2
// Μπορείτε να προκατέχετε τέτοια προβλήματα χρησιμοποιώντας smart coercion με unary + ή - operators:
foo = +document.getElementById("foo-input").value;
// ^ unary + operator θα μετατρέψουν το δεξιά operand σε αριθμό
// typeof foo;
// "number"
if ( foo === 1 ) {
importantTask();
}
// `importantTask()` θα κληθεί
```
Παρακάτω είναι μερικές συχνές περιπτώσεις με coercions:
```javascript
// 3.B.2.1
var number = 1,
string = "1",
bool = false;
number;
// 1
number + "";
// "1"
string;
// "1"
+string;
// 1
+string++;
// 1
string;
// 2
bool;
// false
+bool;
// 0
bool + "";
// "false"
```
```javascript
// 3.B.2.2
var number = 1,
string = "1",
bool = true;
string === number;
// false
string === number + "";
// true
+string === number;
// true
bool === number;
// false
+bool === number;
// true
bool === string;
// false
bool === !!string;
// true
```
```javascript
// 3.B.2.3
var array = [ "a", "b", "c" ];
!!~array.indexOf("a");
// true
!!~array.indexOf("b");
// true
!!~array.indexOf("c");
// true
!!~array.indexOf("d");
// false
// Παρατηρείστε πως τα παραπάνω πρέπει να θεωρούνται "unnecessarily clever"
// Να προτιμάτε την φανερή προσέγγιση συγκρίνοντας την επιστρεφόμενη τιμή του
// indexOf, όπως:
if ( array.indexOf( "a" ) >= 0 ) {
// ...
}
```
```javascript
// 3.B.2.4
var num = 2.5;
parseInt( num, 10 );
// είναι το ίδιο με...
~~num;
num >> 0;
num >>> 0;
// Όλα επιστρέφουν 2
// Να θυμάστε βέβαια, πως οι αρνητικοί αριθμοί θα αντιμετωπιστούν διαφορετικά...
var neg = -2.5;
parseInt( neg, 10 );
// είναι το ίδιο με...
~~neg;
neg >> 0;
// Όλα επιστρέφουν -2
// Όμως...
neg >>> 0;
// Θα επιστρέψει 4294967294
```
4. <a name="cond">Conditional Evaluation</a>
```javascript
// 4.1.1
// Όταν ελέγχετε αν ένα array έχει length,
// αντί για αυτό:
if ( array.length > 0 ) ...
// ...να ελέγχετε το truthiness, με αυτόν τον τρόπο:
if ( array.length ) ...
// 4.1.2
// Όταν ελέγχετε ότι ένα array είναι empty,
// αντί για αυτό:
if ( array.length === 0 ) ...
// ...να ελέγχετε το truthiness, με αυτόν τον τρόπο:
if ( !array.length ) ...
// 4.1.3
// Όταν ελέγχετε ότι ένα string δεν είναι empty,
// αντί για αυτό:
if ( string !== "" ) ...
// ...να ελέγχετε το truthiness, με αυτόν τον τρόπο:
if ( string ) ...
// 4.1.4
// Όταν ελέγχετε ότι ένα string _είναι_ empty,
// αντί για αυτό:
if ( string === "" ) ...
// ...να ελέγχετε το falsy-ness, με αυτόν τον τρόπο:
if ( !string ) ...
// 4.1.5
// Όταν ελέγχετε ότι ένα reference είναι true,
// αντί για αυτό:
if ( foo === true ) ...
// ...να το ελέγχετε σαν να το εννωείτε, Επωφεληθείτε από τις ενσωματωμένες δυνατότητες:
if ( foo ) ...
// 4.1.6
// Όταν ελέγχετε ότι ένα reference είναι false,
// αντί για αυτό:
if ( foo === false ) ...
// ...να χρησιμποιείτε negation για να κάνετε coerce ένα true evaluation
if ( !foo ) ...
// ...Προσοχή, αυτό θα ισχύει και για: 0, "", null, undefined, NaN
// Αν _ΠΡΕΠΕΙ_ να ελέγξετε ένα boolean false, τότε να χρησιμποιείτε
if ( foo === false ) ...
// 4.1.7
// Όταν ελέγχετε έμα ref που μπορεί να είναι null ή undefined, αλλά ΟΧΙ false, "" or 0,
// αντί για αυτό:
if ( foo === null || foo === undefined ) ...
// ...εκμεταλευτείτε το == type coercion, με αυτόν τον τρόπο:
if ( foo == null ) ...
// Να θυμάστε πως η χρήση == θα ταιριάξει ένα `null` και στο `null` και στο `undefined`
// αλλά όχι `false`, "" ή 0
null == undefined
```
Πάντα να ελέγχετε για το καλύτερο, πιο ακριβές αποτέλεσμα - τα παραπάνω είναι μια κατευθυντήρια γραμμή, όχι ένα δόγμα.
```javascript
// 4.2.1
// Type coercion και evaluation notes
// Να προτιμάρε `===` αντί για `==` (εκτός και αν αυτή η περίπτωση απαιτεί loose type evaluation)
// === δεν κάνει coerce το type, που σημαίνει ότι:
"1" === 1;
// false
// == κάνει coerce type, που σημαίνει ότι:
"1" == 1;
// true
// 4.2.2
// Booleans, Truthies & Falsies
// Booleans:
true, false
// Truthy:
"foo", 1
// Falsy:
"", 0, null, undefined, NaN, void 0
```
5. <a name="practical">Πρακτικό στυλ</a>
```javascript
// 5.1.1
// Ένα Practical Module
(function( global ) {
var Module = (function() {
var data = "secret";
return {
// Αυτό είναι boolean property
bool: true,
// Ένα string value
string: "a string",
// Ένα array property
array: [ 1, 2, 3, 4 ],
// Ένα object property
object: {
lang: "en-Us"
},
getData: function() {
// Επιστρέφει την τωρινή τιμή του `data`
return data;
},
setData: function( value ) {
// θέτει την τιμή του `data` και την επιστρέφει
return ( data = value );
}
};
})();
// Άλλα πράγματα μπορούν να γίνουν εδώ
// Έκθεση του module στο global object
global.Module = Module;
})( this );
```
```javascript
// 5.2.1
// Ένα Practical Constructor
(function( global ) {
function Ctor( foo ) {
this.foo = foo;
return this;
}
Ctor.prototype.getFoo = function() {
return this.foo;
};
Ctor.prototype.setFoo = function( val ) {
return ( this.foo = val );
};
// Για να καλέσετε constructor χωρίς `new`, μπορείτε να κάνετε αυτό:
var ctor = function( foo ) {
return new Ctor( foo );
};
// Έκθεση του constructor στο global object
global.ctor = ctor;
})( this );
```
6. <a name="naming">Ονομασία</a>
A. Δεν είστε code compiler/compressor, οπότε μην προσπαθείτε να είστε ένας.
Ο ακόλουθος κώδικας είναι ένα παράδειγμα από ανήκουστη ονομασία:
```javascript
// 6.A.1.1
// Παράδειγμα κώδικα με φτωχή ονομασία
function q(s) {
return document.querySelectorAll(s);
}
var i,a=[],els=q("#foo");
for(i=0;i<els.length;i++){a.push(els[i]);}
```
Χωρίς αμφιβολία, έχετε γράψει κώδικα σαν και αυτόν - εύχομαι να τελειώσει σήμερα αυτό.
Παρακάτω είναι η ίδια λογική, αλλά με πιο καλή ονομασία (ευανάγνωστη δομή):
```javascript
// 6.A.2.1
// Παράδειγμα κώδικα με βελτιωμένη ονομασία
function query( selector ) {
return document.querySelectorAll( selector );
}
var idx = 0,
elements = [],
matches = query("#foo"),
length = matches.length;
for ( ; idx < length; idx++ ) {
elements.push( matches[ idx ] );
}
```
Λίγοι επιπλέον δείκτες ονομασίας:
```javascript
// 6.A.3.1
// Ονομάζοντας strings
`dog` είναι ένα string
// 6.A.3.2
// Ονομάζοντας arrays
`dogs` είναι ένα array από `dog` strings
// 6.A.3.3
// Ονομάζοντας functions, objects, instances, κλπ
camelCase; function and var declarations
// 6.A.3.4
// Ονομάζοντας constructors, prototypes, etc.
PascalCase; constructor function
// 6.A.3.5
// Ονομάζοντας regular expressions
rDesc = //;
// 6.A.3.6
// Από το Google Closure Library Style Guide
functionNamesLikeThis;
variableNamesLikeThis;
ConstructorNamesLikeThis;
EnumNamesLikeThis;
methodNamesLikeThis;
SYMBOLIC_CONSTANTS_LIKE_THIS;
```
B. Περιπτώσεις από το `this`
Εκτός από τις γενικά γνωστές περιπτώσεις του `call` και του `apply`, πάντα να προτιμάτε το `.bind( this )` ή ένα functional equivalent, για να δημιουργείτε `BoundFunction` definitions για μελλοντική χρήση. Χρησιμοποιείτε μόνο ψευδώνυμα όταν δεν υπάρχει διαθέσιμη επιλογή.
```javascript
// 6.B.1
function Device( opts ) {
this.value = null;
// ανοίξτε ένα async stream,
// αυτό θα καλείαι συνεχόμενα
stream.read( opts.path, function( data ) {
// Ανανεώστε αυτού του instance την τιμή
// με την πιο πρόσφατη τιμή από το
// data stream
this.value = data;
}.bind(this) );
// Πετάξτε τη συχνότητα των συμβάντων που εκπέμπονται από
// αυτήν την εμφάνιση συσκευής
setInterval(function() {
// Εκπέμπει ένα throttled event
this.emit("event");
}.bind(this), opts.freq || 100 );
}
// Απλά προσποιηθείτε ότι κάναμε inherit EventEmitter ;)
```
Όταν δεν είναι διαθέσιμες, λειτουργικά ισοδύναμα με το `.bind` υπάρχουν σε πολλές σύγχρονες βιβλιοθήκες JavaScript.
```javascript
// 6.B.2
// πχ. lodash/underscore, _.bind()
function Device( 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 );
}
// πχ. jQuery.proxy
function Device( 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 );
}
// πχ. dojo.hitch
function Device( 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 );
}
```
Ως έσχατη λύση, δημιουργήστε ένα ψευδώνυμο στο `this 'χρησιμοποιώντας `self` ως αναγνωριστικό. Αυτό είναι εξαιρετικά επιρρεπές στο σφάλμα και θα πρέπει να αποφεύγεται όποτε είναι δυνατόν.
```javascript
// 6.B.3
function Device( opts ) {
var self = this;
this.value = null;
stream.read( opts.path, function( data ) {
self.value = data;
});
setInterval(function() {
self.emit("event");
}, opts.freq || 100 );
}
```
C. Χρήση `thisArg`
Αρκετές πρωτότυπες μέθοδοι των ενσωματωμένων ES 5.1 έρχονται με μια ειδική υπογραφή `thisArg`, η οποία θα πρέπει να χρησιμοποιείται όποτε είναι δυνατόν
```javascript
// 6.C.1
var obj;
obj = { f: "foo", b: "bar", q: "qux" };
Object.keys( obj ).forEach(function( key ) {
// |this| τώρα αναφέρεται στο `obj`
console.log( this[ key ] );
}, obj ); // <-- το τελευταίο arg είναι το `thisArg`
// Εκτυπώνει...
// "foo"
// "bar"
// "qux"
```
`thisArg` μπορεί να χρησιμοποιηθεί με `Array.prototype.every`, `Array.prototype.forEach`, `Array.prototype.some`, `Array.prototype.map`, `Array.prototype.filter`
7. <a name="misc">Διάφορα</a>
Αυτή η ενότητα θα χρησιμεύσει για να Εικονογραφηθούν ιδέες και έννοιες που δεν πρέπει να θεωρούνται δόγμα, αλλά αντίθετα υπάρχουν για να ενθαρρύνουμε τις πρακτικές αμφισβήτησης σε μια προσπάθεια να βρούμε καλύτερους τρόπους για να κάνουμε κοινές εργασίες προγραμματισμού JavaScript.
A. Η χρήση του `switch` πρέπει να αποφεύγεται, ο σύγχρονος εντοπισμός μεθόδων θα περιλαμβάνει μαύρες λίστες με εντολές μεταγωγής
Φαίνεται να υπάρχουν δραστικές βελτιώσεις στην εκτέλεση των δηλώσεων `switch` στις τελευταίες εκδόσεις του Firefox και του Chrome.
http://jsperf.com/switch-vs-object-literal-vs-module
Σημαντικές βελτιώσεις μπορούν να παρατηρηθούν και εδώ:
https://github.com/rwldrn/idiomatic.js/issues/13
```javascript
// 7.A.1.1
// Ένα παράδειγμα switch statement
switch( foo ) {
case "alpha":
alpha();
break;
case "beta":
beta();
break;
default:
// κάτι στο οποίο να κάνει default
break;
}
// 7.A.1.2
// Μια εναλλακτική προσέγγιση που υποστηρίζει τη δυνατότητα σύνθεσης και επαναχρησιμοποίησης είναι
// η χρήση ενός αντικειμένου για την αποθήκευση "cases" και ένα function για την ανάθεση:
var cases, delegator;
// Παράδειγμα επιστρέφει μόνο για απεικόνιση.
cases = {
alpha: function() {
// statements
// ένα return
return [ "Alpha", arguments.length ];
},
beta: function() {
// statements
// ένα return
return [ "Beta", arguments.length ];
},
_default: function() {
// statements
// ένα return
return [ "Default", arguments.length ];
}
};
delegator = function() {
var args, key, delegate;
// Μετατρέψτε το arguments list σε ένα array
args = [].slice.call( arguments );
// shift το case key από τα arguments
key = args.shift();
// Αναθέστε το default case handler
delegate = cases._default;
// Derive the method to delegate operation to
if ( cases.hasOwnProperty( key ) ) {
delegate = cases[ key ];
}
// Τα scope arg θα μπορούσαν να ανατεθούν σε κάτι συγκεκριμένο,
// σε αυτήν την περίπτωση το |null| θα ήταν αρκετό
return delegate.apply( null, args );
};
// 7.A.1.3
// Κάντε το API από το 7.A.1.2 να δουλέψει:
delegator( "alpha", 1, 2, 3, 4, 5 );
// [ "Alpha", 5 ]
// Φυσικά, το `case` key argument θα μπορούσε έυκολα να είναι βασισμένο
// σε κάποιο άλλο τυχαίο condition.
var caseKey, someUserInput;
// Πιθανών κάποιου είδους form input;
someUserInput = 9;
if ( someUserInput > 10 ) {
caseKey = "alpha";
} else {
caseKey = "beta";
}
// ή...
caseKey = someUserInput > 10 ? "alpha" : "beta";
// Ύστερα...
delegator( caseKey, someUserInput );
// [ "Beta", 1 ]
// Και φυσικά...
delegator();
// [ "Default", 0 ]
```
B. Οι πρώτες επιστροφές προάγουν την αναγνωσιμότητα του κώδικα με αμελητέα διαφορά απόδοσης
```javascript
// 7.B.1.1
// Κακό:
function returnLate( foo ) {
var ret;
if ( foo ) {
ret = "foo";
} else {
ret = "quux";
}
return ret;
}
// Καλό:
function returnEarly( foo ) {
if ( foo ) {
return "foo";
}
return "quux";
}
```
8. <a name="native">Native & Host Objects</a>
Η βασική αρχή εδώ είναι:
### Μην κάνετε χαζές βλακείες και όλα θα δουλεύουν καλά.
Για να ενισχύσετε αυτήν την έννοια, παρακαλούμε δείτε την ακόλουθη παρουσίαση:
#### “Everything is Permitted: Extending Built-ins” του Andrew Dupont (JSConf2011, Portland, Oregon)
https://www.youtube.com/watch?v=xL3xCO7CLNM
9. <a name="comments">Σχόλια</a>
#### Μονή γραμμή πάνς από τον κώδικα είναι υποκειμενικό
#### Πολλαπλή γραμμή είναι καλή
#### Τα σχόλια στο τέλος της γραμμής απαγορεύονται!
#### Το JSDoc στυλ είναι καλό, αλλά απαιτεί μια σημαντική επένδυση χρόνου
10. <a name="language">Ένας κώδικας γλώσσας</a>
Τα προγράμματα πρέπει να είναι γραμμένα σε μία γλώσσα, όποια και αν είναι αυτή η γλώσσα, όπως υπαγορεύει ο διαχειριστής ή οι συντηρητές.
## Παράρτημα
### Comma First.
Οποιοδήποτε project που παραθέτει αυτό το έγγραφο ως βασικό οδηγό στυλ δεν θα δεχτεί μορφοποίηση πρώτου κώδικα με κόμμα, εκτός εάν έχει οριστεί διαφορετικά από τον συντάκτη του project.
----------
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/80x15.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Principles of Writing Consistent, Idiomatic JavaScript</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/rwldrn/idiomatic.js" property="cc:attributionName" rel="cc:attributionURL">Rick Waldron and Contributors</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/rwldrn/idiomatic.js" rel="dct:source">github.com/rwldrn/idiomatic.js</a>.
================================================
FILE: translations/hi_HI/readme.md
================================================
# जावास्क्रिप्ट लेखन के स्थिर एवं सिद्धप्रयोग सिद्धांत
## यह एक जीवित आलेख है और कोड को उत्तमतर बनाने हेतु नए विचारों का सर्वदा स्वागत है | योगदान: fork, clone, branch, commit, push, pull request.
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwaldron)
* Mathias Bynens [@mathias](http://twitter.com/mathias), [github](https://github.com/mathiasbynens)
* Schalk Neethling [@ossreleasefeed](http://twitter.com/ossreleasefeed), [github](https://github.com/ossreleasefeed/)
* Kit Cambridge [@kitcambridge](http://twitter.com/kitcambridge), [github](https://github.com/kitcambridge)
* Raynos [github](https://github.com/Raynos)
* Matias Arriola [@MatiasArriola](https://twitter.com/MatiasArriola), [github](https://github.com/MatiasArriola/)
* John Fischer [@jfroffice](https://twitter.com/jfroffice), [github](https://github.com/jfroffice/)
* Idan Gazit [@idangazit](http://twitter.com/idangazit), [github](https://github.com/idan)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
* Breno Oliveira [@garu_rj](http://twitter.com/garu_rj), [github](https://github.com/garu)
* Leo Beto Souza [@leobetosouza](http://twitter.com/leobetosouza), [github](https://github.com/leobetosouza)
* Ryuichi Okumura [@okuryu](http://twitter.com/okuryu), [github](https://github.com/okuryu)
* Pascal Precht [@PascalPrecht](http://twitter.com/PascalPrecht), [github](https://github.com/pascalprecht)
* EngForDev [engfordev](https://opentutorials.org/course/245/1788) - Hwan Min Hong / MinTaek Kwon [@leoinsight](http://twitter.com/leoinsight) / Tw Shim [@marocchino](http://twitter.com/marocchino), [github](https://github.com/marocchino) / Nassol Kim [@nassol99](http://twitter.com/nassol99), [github](https://github.com/nassol) / Juntai Park [@rkJun](http://twitter.com/rkJun), [github](https://github.com/rkJun) / Minkyu Shim / Gangmin Won / Justin Yoo [@justinchronicle](http://twitter.com/justinchronicle) / Daeyup Lee
* Marco Trulla [@marcotrulla](http://twitter.com/marcotrulla), [github](https://github.com/Ragnarokkr)
* Alex Navasardyan [@alexnavasardyan](http://twitter.com/alexnavasardyan), [github](https://github.com/2k00l)
* Mihai Paun [@mihaipaun](http://twitter.com/mihaipaun), [github](https://github.com/mihaipaun)
* Evgeny Mandrikov [@\_godin\_](http://twitter.com/_godin_), [github](https://github.com/Godin)
* Sofish Lin [@sofish](http://twitter.com/sofish), [github](https://github.com/sofish)
* Дејан Димић [@dejan_dimic](http://twitter.com/dejan_dimic), [github](https://github.com/rubystream)
* Miloš Gavrilović [@gavrisimo](http://twitter.com/gavrisimo), [github](https://github.com/gavrisimo)
* Firede [@firede](https://twitter.com/firede) [github](https://github.com/firede)
* monkadd [github](https://github.com/monkadd)
* Stephan Lindauer [@stephanlindauer](http://twitter.com/stephanlindauer), [github](https://github.com/stephanlindauer)
* Thomas P [@dragon5689](https://twitter.com/dragon5689) [github](https://github.com/dragon5689)
* Yotam Ofek [@yotamofek](https://twitter.com/yotamofek) [github](https://github.com/yotamofek)
* Aleksandr Filatov [@greybax](http://twitter.com/greybax), [github](https://github.com/greybax)
* Duc Nguyen [@ducntq](https://twitter.com/ducntq), [github](https://github.com/ducntq)
* James Young [@jamsyoung](http://twitter.com/jamsyoung), [github](https://github.com/jamsyoung)
* Hao-Wei Jeng [@l0ckys](http://twitter.com/l0ckys), [github](https://github.com/lockys)
* Richard Gibson [@gibson042](http://twitter.com/gibson042), [github](https://github.com/gibson042)
* Fesuy [github](https://github.com/fesuydev)
* Stephane Moreau [github](https://github.com/stmoreau)
* Akshat Joshi [@akshat_joshi](http://twitter.com/akshat_joshi), [github](https://https://github.com/akshatjoshii)
## किसी भी कोड-बेस का कोड ऐसा दिखना चाहिए जैसे एक ही व्यक्ति ने मानो पूरा कोड लिखा हो, भले ही कितने लोगों का उसमें योगदान रहा हो |
### निम्नलिखित सूची उन तरीकों को रेखांकित करती है जो मैं अपने कोड मे प्रयोग करता हूँ, जिनका मैं वास्तविक लेखक हूँ ; मेरे द्वारा रचित प्रोजे
gitextract_w5co02kf/
├── .gitattributes
├── .gitignore
├── cc-license.md
├── contributors.md
├── readme.md
└── translations/
├── bg_BG/
│ └── readme.md
├── de_DE/
│ └── readme.md
├── es_ES/
│ └── readme.md
├── fr_FR/
│ └── readme.md
├── gr_GR/
│ └── readme.md
├── hi_HI/
│ └── readme.md
├── id_ID/
│ └── readme.md
├── it_IT/
│ └── readme.md
├── ja_JP/
│ └── readme.md
├── ko_KR/
│ └── readme.md
├── pl_PL/
│ └── readme.md
├── pt_BR/
│ └── readme.md
├── ro_RO/
│ └── readme.md
├── ru_RU/
│ └── readme.md
├── sr_SR/
│ └── readme.md
├── vi_VN/
│ └── readme.md
├── zh_CN/
│ └── readme.md
├── zh_TW/
│ └── readme.md
└── ср_СР/
└── readme.md
Condensed preview — 24 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (648K chars).
[
{
"path": ".gitattributes",
"chars": 7,
"preview": "eol=lf\n"
},
{
"path": ".gitignore",
"chars": 98,
"preview": ".DS_Store\n*.swp\ndist\nkits/makefile-kit/dist\nkits/jakefile-kit/dist\nkits/jakefile-kit/node_modules\n"
},
{
"path": "cc-license.md",
"chars": 898,
"preview": "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/3.0/deed.en_US\"><img alt=\"Creative Commons License\" style="
},
{
"path": "contributors.md",
"chars": 3626,
"preview": "* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwldrn)\n* Mathias Bynens [@mathias]"
},
{
"path": "readme.md",
"chars": 33490,
"preview": "# Principles of Writing Consistent, Idiomatic JavaScript\n\n\n## This is a living document and new ideas for improving the "
},
{
"path": "translations/bg_BG/readme.md",
"chars": 34501,
"preview": "# Принципи на консистентно и идиоматично писане на JavaScript\n\n## Това е \"жив\" документ и нови идеи за подобряване на ко"
},
{
"path": "translations/de_DE/readme.md",
"chars": 26823,
"preview": "# Grundsätze für das Schreiben von konsequentem und idiomatischem JavaScript\n\n## Dies ist ein lebendiges Dokument und ne"
},
{
"path": "translations/es_ES/readme.md",
"chars": 34487,
"preview": "# Principios para escribir JavaScript consistente e idiomático\n\n\n## Este es un documento vivo, y nuevas ideas para mejor"
},
{
"path": "translations/fr_FR/readme.md",
"chars": 25985,
"preview": "# Principes d'écriture d'un code JavaScript cohérent et idiomatique\n\n## Il s'agit d'un document vivant, les nouvelles id"
},
{
"path": "translations/gr_GR/readme.md",
"chars": 34578,
"preview": "# Αρχές γραφής συνεπούς και ιδιοματικής Javascript\n\n\n\n## Αυτό είναι απλά ένα αρχείο και νέες ιδέες που βελτιώνουν τον κώ"
},
{
"path": "translations/hi_HI/readme.md",
"chars": 34434,
"preview": "# जावास्क्रिप्ट लेखन के स्थिर एवं सिद्धप्रयोग सिद्धांत \n\n\n## यह एक जीवित आलेख है और कोड को उत्तमतर बनाने हेतु नए विचारो"
},
{
"path": "translations/id_ID/readme.md",
"chars": 34432,
"preview": "# Principles of Writing Consistent, Idiomatic JavaScript\n\n\n## This is a living document and new ideas for improving the "
},
{
"path": "translations/it_IT/readme.md",
"chars": 34710,
"preview": "# Princìpi per la scrittura di JavaScript consistente ed idiomatico\n\n\n## Questo è un documento in continua evoluzione e "
},
{
"path": "translations/ja_JP/readme.md",
"chars": 25108,
"preview": "# 一貫性のある慣用的なJavaScriptの書き方\n\n\n## これは継続しているドキュメントであるため、私たちのコードを改善できる新しいアイデアを常に歓迎します。貢献方法: fork、clone、branch、commit、push、pu"
},
{
"path": "translations/ko_KR/readme.md",
"chars": 27111,
"preview": "# 자연스럽고 일관성 있게 자바스크립트 코딩하는 원칙\n\n## 이 문서는 계속 바뀝니다. 주변의 코드를 더 낫게 만들기 위한 좋은 아이디어가 있으시면 알려주세요. Github에서 fork, clone, branch, "
},
{
"path": "translations/pl_PL/readme.md",
"chars": 31330,
"preview": "# Zasady pisania zwartego, idiomatycznego kodu JavaScript\n\n\n## Dokument który czytasz powstał dzięki współpracy wielu lu"
},
{
"path": "translations/pt_BR/readme.md",
"chars": 31785,
"preview": "# Princípios para Escrever JavaScript de forma Consistente e Idiomática\n\n## Este é um documento vivo e novas ideias para"
},
{
"path": "translations/ro_RO/readme.md",
"chars": 31471,
"preview": "# Principii de codare consistentă și idiomatică în JavaScript\n\n\n## Acesta este un document în continuă dezvoltare și noi"
},
{
"path": "translations/ru_RU/readme.md",
"chars": 30344,
"preview": "# Принципы написания консистентного, идиоматического кода на JavaScript ***\n\n## Это \"живой\" документ и новые идеи по улу"
},
{
"path": "translations/sr_SR/readme.md",
"chars": 32046,
"preview": "# Principi pisanja konzistentnog, idiomatskog JavaScript-a\n\n\n## Ovo je \"živ\" dokument i nove ideje za unapređenje koda o"
},
{
"path": "translations/vi_VN/readme.md",
"chars": 28596,
"preview": "# Nguyên tắc để Viết Javascript Nhất quán\n\n\n## Đây là một tài liệu sống và những ý tưởng để nâng cao chất lượng code xun"
},
{
"path": "translations/zh_CN/readme.md",
"chars": 23692,
"preview": "# 书写具备一致风格、通俗易懂 JavaScript 的原则\n\n## 这是一份用来改进我们代码,以让其总是让人喜爱的持续更新的文档(living document)和新思想。参与构建:(请)fork、clone、branch、commit、"
},
{
"path": "translations/zh_TW/readme.md",
"chars": 25365,
"preview": "# 撰寫一致風格且通順易懂的 JavaScript 之原則\n\n## 這是一份持續更新的文件,歡迎任何對於增進本文件內程式碼的想法。參與貢獻:fork、clone、branch、commit、push、pull、pull request。\n\n"
},
{
"path": "translations/ср_СР/readme.md",
"chars": 30911,
"preview": "# Принципи писања Конзистентног, Идиоматског JavaScript-а\n\n\n## Ово је \"жив\" документ и нове идеје за унапређење кода око"
}
]
About this extraction
This page contains the full source code of the rwaldron/idiomatic.js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 24 files (601.4 KB), approximately 188.6k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.