You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/02-coding-style/article.md
+75-77Lines changed: 75 additions & 77 deletions
Original file line number
Diff line number
Diff line change
@@ -50,10 +50,9 @@ if (condition) {
50
50
}
51
51
```
52
52
53
-
A single-line construct is an important edge case. Should we use brackets at all? If yes, then where?
54
-
55
-
Here are the annotated variants so you can judge their readability for yourself:
53
+
En una construccion de una sola linea es un caso extremo importante. ¿Debemos usar llaves? Si si, entonces ¿donde?
56
54
55
+
Aqui estan las variantes anotadas para que puedas juzgar la legibilidad por ti mismo.
57
56
<!--
58
57
```js no-beautify
59
58
if (n < 0) {alert(`Power ${n} is not supported`);}
@@ -70,31 +69,30 @@ if (n < 0) {
70
69
-->
71
70

72
71
73
-
In summary:
74
-
- For very short code, one line is acceptable. For example: `if (cond) return null`.
75
-
- But a separate line for each statement in brackets is usually easier to read.
76
-
77
-
### Line Length
72
+
En resumen:
73
+
- Para codigo muy corto, una linea es aceptable. Por ejemplo: `if (cond) return null`
74
+
- Pero en una linea separada por cada sentencia en llaves es usualmente mas facil de leer.
78
75
79
-
No one likes to read a long horizontal line of code. It's best practice to split them up and limit the length of your lines.
76
+
### Tamaño de linea
80
77
81
-
The maximum line length should be agreed upon at the team-level. It's usually 80 or 120 characters.
78
+
Nadie le gusta leer una linea horizontal larga de codigo. Es una mejor practica dividirlas y limitar el tamaño de tus lineas.
82
79
83
-
### Indents
80
+
El maximo tamaño de linea deberia ser acordado en el livel de equipo. Es usualmente 80 o 120 caracteres.
81
+
### Identaciones
84
82
85
-
There are two types of indents:
83
+
Hay dos tipo de identaciones:
86
84
87
-
-**Horizontal indents: 2 or 4 spaces.**
85
+
-**Identacion horizontal: 2 o 4 espacios.**
88
86
89
-
A horizontal indentation is made using either 2 or 4 spaces or the "Tab" symbol. Which one to choose is an old holy war. Spaces are more common nowadays.
87
+
Una identacion horizontal es hecha usando 2 o 4 espacios o el simbolo "Tab". ¿Cual elegir? es una vieja guerra santa. Espacios son mas comunes en estos dias.
90
88
91
-
One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the "Tab" symbol.
89
+
Una ventaja de los espacios sobre las tabulaciones es que los espacios permiten mas configuraciones flexibles de identaciones en lugar del simbolo "Tab".
92
90
93
-
For instance, we can align the arguments with the opening bracket, like this:
91
+
Por instancia, nosotros podemos alinear los argumentos con la llave de apertura, como esto:
94
92
95
93
```js no-beautify
96
94
show(parameters,
97
-
aligned, // 5 spaces padding at the left
95
+
aligned, // 5 espacios de relleno a la izquierda
98
96
one,
99
97
after,
100
98
another
@@ -103,9 +101,9 @@ There are two types of indents:
103
101
}
104
102
```
105
103
106
-
-**Vertical indents: empty lines for splitting code into logical blocks.**
104
+
-**Identacion vertical: lineas vacias para dividir codigo en bloques logicos.**
107
105
108
-
Even a single function can often be divided into logical blocks. In the example below, the initialization of variables, the main loop and returning the result are split vertically:
106
+
Aun una simple funcion puede a menudo ser dividida en bloques logicos. En el ejemplo abajo, la inicializacion de variables, el bucle principal y el retorno del resultado son divididos verticalmente:
109
107
110
108
```js
111
109
function pow(x, n) {
@@ -119,46 +117,46 @@ There are two types of indents:
119
117
}
120
118
```
121
119
122
-
Insert an extra newline where it helps to make the code more readable. There should not be more than nine lines of code without a vertical indentation.
120
+
Insertar una nueva linea extra donde ayude a hacer el codigo mas legible. No debe de haber mas de nueve lineas de codigo sin una identacion vertical.
123
121
124
-
### Semicolons
122
+
### Punto y coma
125
123
126
-
A semicolon should be present after each statement, even if it could possibly be skipped.
124
+
Un punto y coma debe estar presente despues de cada sentencia, aun si podria posiblemente ser omitido.
127
125
128
-
There are languages where a semicolon is truly optional and it is rarely used. In JavaScript, though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors.
126
+
Hay lenguajes donde un punto y coma es verdaderamente opcional y es raramente usado. En Javascript, hay casos donde un salto de linea no es interpretado como un punto y coma, dejando el codigo vulnerable a errores.
129
127
130
-
As you become more mature as a programmer, you may choose a no-semicolon style like [StandardJS](https://standardjs.com/). Until then, it's best to use semicolons to avoid possible pitfalls.
128
+
A medida tu te conviertas en un programador mas maduro, podrias escoger un estilo no-semicolon como [StandardJS](https://standardjs.com/). Hasta entonces, es mejor usar puntos y comas para evitar posibles dificultades.
131
129
132
-
### Nesting Levels
130
+
### Niveles anidados
133
131
134
-
Try to avoid nesting code too many levels deep.
132
+
Intenta evitar anidar el codigo en demasiados niveles de profuncidad.
135
133
136
-
Sometimes it's a good idea to use the ["continue"](info:while-for#continue) directive in a loop to avoid extra nesting.
134
+
Algunas veces es buena idea usar la directiva ["continue"](info:while-for#continue) en un bucle para evitar anidamiento extra.
137
135
138
-
For example, instead of adding a nested `if` conditional like this:
136
+
Por ejemplo, en lugar de añadir un`if`anidado como este:
139
137
140
138
```js
141
139
for (let i = 0; i < 10; i++) {
142
140
if (cond) {
143
-
... // <- one more nesting level
141
+
... // <- un nivel mas de anidamiento
144
142
}
145
143
}
146
144
```
147
145
148
-
We can write:
146
+
Podemos escribir:
149
147
150
148
```js
151
149
for (let i = 0; i < 10; i++) {
152
-
if (!cond) *!*continue*/!*;
153
-
... // <- no extra nesting level
150
+
if (!cond) continue;
151
+
... // <- sin nivel extra de anidamiento
154
152
}
155
153
```
156
154
157
-
A similar thing can be done with `if/else` and `return`.
155
+
Una similar cosa puede ser hecho con`if/else`y`return`.
158
156
159
-
For example, two constructs below are identical.
157
+
Por ejemplo, dos construcciones abajo son identicas.
160
158
161
-
Option 1:
159
+
Opcion1:
162
160
163
161
```js
164
162
function pow(x, n) {
@@ -176,7 +174,7 @@ function pow(x, n) {
176
174
}
177
175
```
178
176
179
-
Option 2:
177
+
Opcion2:
180
178
181
179
```js
182
180
function pow(x, n) {
@@ -195,16 +193,16 @@ function pow(x, n) {
195
193
}
196
194
```
197
195
198
-
The second one is more readable because the "edge case" of `n < 0` is handled early on. Once the check is done we can move on to the "main" code flow without the need for additional nesting.
196
+
El segundo es mas legible porque el "caso extremo" de`n < 0`se maneja desde el principio. Una vez el chequeo es terminado nosotros nos podemos mover a el codigo "main"el codigo fluye sin necesidad de anidamientos adicionales.
199
197
200
-
## Function Placement
198
+
## Colocacion de funciones
201
199
202
-
If you are writing several "helper" functions and the code that uses them, there are three ways to organize the functions.
200
+
Si estas escribiendo varias funciones "auxiliares" y el codigo que las usan, hay tres maneras de organizar funciones.
203
201
204
-
1. Functions declared above the code that uses them:
202
+
1.Funciones declaradas sobre el codigo que las usan:
205
203
206
204
```js
207
-
// *!*function declarations*/!*
205
+
// *!*declaracion de funciones*/!*
208
206
function createElement() {
209
207
...
210
208
}
@@ -217,20 +215,20 @@ If you are writing several "helper" functions and the code that uses them, there
217
215
...
218
216
}
219
217
220
-
// *!*the code which uses them*/!*
218
+
// *!*el codigo que las usan*/!*
221
219
let elem = createElement();
222
220
setHandler(elem);
223
221
walkAround();
224
222
```
225
-
2. Code first, then functions
223
+
2.Codigo primero, despues funciones
226
224
227
225
```js
228
-
// *!*the code which uses the functions*/!*
226
+
// *!*El codigo que usa a las funciones*/!*
229
227
let elem = createElement();
230
228
setHandler(elem);
231
229
walkAround();
232
230
233
-
// --- *!*helper functions*/!* ---
231
+
// --- *!*Funciones auxiliares*/!* ---
234
232
function createElement() {
235
233
...
236
234
}
@@ -243,54 +241,54 @@ If you are writing several "helper" functions and the code that uses them, there
243
241
...
244
242
}
245
243
```
246
-
3. Mixed: a function is declared where it's first used.
244
+
3.Mixto: una funcion es declarada donde se usa por primera vez.
247
245
248
-
Most of time, the second variant is preferred.
246
+
La mayoria del tiempo, la segunda variante es preferida.
249
247
250
-
That's because when reading code, we first want to know *what it does*. If the code goes first, then it provides that information. Then, maybe we won't need to read the functions at all, especially if their names are descriptive of what they actually do.
248
+
Eso es por que cuando leemos codigo, nosotros primero queremos saber *Que hace*. Si el codigo va primero, entonces provee esa informacion. entonces, quizas nosotros no necesitaremos leer las funciones, especialmente si sus nombres son descriptivos de lo que realmente hacen.
251
249
252
-
## Style Guides
250
+
## Guias de estilo
253
251
254
-
A style guide contains general rules about "how to write" code, e.g. which quotes to use, how many spaces to indent, where to put line breaks, etc. A lot of minor things.
252
+
Una guia de estilo contine reglas generales acerca de "Como escribir codigo", por ejemplo. Que comillas usar, cuantos espacios de identacion, donde poner los saltos de linea, etc. Muchas cosas pequeñas.
255
253
256
-
When all members of a team use the same style guide, the code looks uniform, regardless of which team member wrote it.
254
+
Cuando todos los mienbros de un equipo usan la misma guia de estilos, el codigo se ve uniforme, sin importar de cual mienbro del equipo lo escriba.
257
255
258
-
Of course, a team can always write their own style guide. Mostof the time though, there's no need to. There are many existing tried and true options to choose from, so adopting one of these is usually your best bet.
256
+
Por supuesto, un equipo puede siempre escribir su propia guia de estilos. Aunque la mayoria del tiempo, no es necesario. Hay varios otros existentes probados y verdaderas opciones para escoger, asi adoptando una de estas es usualmente tu mejor opcion.
If you're a novice developer, start with the cheatsheet at the beginning ofthischapter. Once you've mastered that you can browse other style guides to pick up common principles and decide which one you like best.
266
+
Si tu eres un desarrollador novato, empieza con la cheatsheet al inicio de este capitulo. Una vez tu hayas dominado eso, puedes explorar otras guias de estilos para coger principios comunes y decidir cual te gusta mas.
269
267
270
-
## Automated Linters
268
+
## Linters automatizados
271
269
272
-
Linters are tools that can automatically check the style of your code and make suggestions for refactoring.
270
+
Linters son herramientas que pueden automaticamente verificar el estilo de tu codigo y hacer sugerencias y refactorizacion.
273
271
274
-
The great thing about them is that style-checking can also find some bugs, like typos in variable or function names. Because of this feature, installing a linter is recommended even if you don't want to stick to one particular "code style".
272
+
Lo grandioso de ellos es que la comprobacion de estilo tambien puede encontrar algunos bugs, como errores gramaticales en variables o nombres de funciones. Debido a estas caracteristicas, Instalar un linter es comendado aun si tu no quieres apegarte a un "estilo de codigo" en particular.
275
273
276
-
Here are the most well-known linting tools:
274
+
Estas son las herramientas de linting mas conocidas:
277
275
278
-
- [JSLint](http://www.jslint.com/) -- one of the first linters.
279
-
- [JSHint](http://www.jshint.com/) -- more settings than JSLint.
280
-
- [ESLint](http://eslint.org/) -- probably the newest one.
276
+
- [JSLint](http://www.jslint.com/) -- uno de los primeros linters.
277
+
- [JSHint](http://www.jshint.com/) -- mas ajustes que JSLint.
278
+
- [ESLint](http://eslint.org/) -- probablemente el mas reciente.
281
279
282
-
All of them can do the job. The author uses [ESLint](http://eslint.org/).
280
+
Todos ellos pueden hacer el trabajo. El author usa [ESLint](http://eslint.org/).
283
281
284
-
Most linters are integrated with many popular editors: just enable the plugin in the editor and configure the style.
282
+
Muchos linters son integrados con varios editores populares: solo habilite el plugin en el editor y configure el estilo.
285
283
286
-
For instance, for ESLint you should do the following:
284
+
Por ejemplo, para ESLint tu puedes hacer lo siguiente:
287
285
288
-
1.Install [Node.JS](https://nodejs.org/).
289
-
2.Install ESLint with the command`npm install -g eslint` (npm is a JavaScript package installer).
290
-
3.Create a config file named `.eslintrc`in the root of your JavaScript project (in the folder that contains all your files).
291
-
4.Install/enable the plugin for your editor that integrates withESLint. The majority of editors have one.
286
+
1.Instala [Node.JS](https://nodejs.org/).
287
+
2.Instala ESLint con el comando`npm install -g eslint` (npm es un instalador de paquetes de Javascript).
288
+
3.Crea un archivo de configuracion llamado `.eslintrc`en la raiz de tu proyecto de javascript (en el folder que contiene todos tus archivos).
289
+
4.Instala/Habilita el plugin para que tu editor se integre conESLint. La mayoria de editores tienen uno.
292
290
293
-
Here's an example of an `.eslintrc` file:
291
+
Aqui un ejemplo de un archivo `.eslintrc`:
294
292
295
293
```js
296
294
{
@@ -307,16 +305,16 @@ Here's an example of an `.eslintrc` file:
307
305
}
308
306
```
309
307
310
-
Here the directive `"extends"` denotes that the configuration is based on the "eslint:recommended" set of settings. After that, we specify our own.
308
+
Aqui la directiva`"extends"`denota que la confifuracion es basada en el conjunto de ajustes "eslint:recommended". Despues de eso, especificamos el nuestro.
311
309
312
-
It is also possible to download style rule sets from the web and extend them instead. See <http://eslint.org/docs/user-guide/getting-started> for more details about installation.
310
+
Es tambien posible descargar el conjunto de reglas de la web y extenderlos en su lugar. Ver<http://eslint.org/docs/user-guide/getting-started> para mas detalles de su instalacion.
313
311
314
-
Also certain IDEs have built-in linting, which is convenient but not as customizable as ESLint.
312
+
Tambien ciertos IDEs tiene linting incorporado, lo cual es conveniente pero no como un ESLint personalizable.
315
313
316
-
## Summary
314
+
## Resumen
317
315
318
-
All syntax rules described in this chapter (and in the style guides referenced) aim to increase the readability of your code, but all of them are debatable.
316
+
Todas las reglas de sintaxis descritas en este capitulo (y en las guias de estilos referenciados) tienen como objetivo incrementar la legibilidad de tu codigo, pero todos ellos son debatibles.
319
317
320
-
When we think about writing "better" code, the questions we should ask are, "What makes the code more readable and easier to understand?" and "What can help us avoid errors?" These are the main things to keep in mind when choosing and debating code styles.
318
+
Cuando nosotros pensamos acerca de escribir "mejor" codigo, las sugerencias que nosotros debemos preguntar son, "¿Que hace que el codigo sea mas legible y facil de entender?"y "¿Que puede ayudarnos a evitar errores?"Estos son las principales cosas a tener en cuenta cuando escogemos y debatimos estilos de codigo.
321
319
322
-
Reading popular style guides will allow you to keep up to date with the latest ideas about code style trends and best practices.
320
+
Leer guias de estilos populares te permitiran mantenerte al dia con las ultimas ideas acerca de tendencias estilos de codigo y mejores practicas.
0 commit comments