Skip to content

Commit b91261d

Browse files
authored
Merge pull request #32 from victorze-forks/code-structure
Code structure
2 parents f57da03 + 239f1b6 commit b91261d

File tree

1 file changed

+68
-66
lines changed

1 file changed

+68
-66
lines changed

1-js/02-first-steps/02-structure/article.md

Lines changed: 68 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,159 +1,161 @@
1-
# Code structure
1+
# Estructura del código
22

3-
The first thing we'll study is the building blocks of code.
3+
Lo primero que estudiaremos son los bloques de construcción del código.
44

5-
## Statements
5+
## Sentencias
66

7-
Statements are syntax constructs and commands that perform actions.
7+
Las sentencias son construcciones sintácticas y comandos que realizan acciones.
88

9-
We've already seen a statement, `alert('Hello, world!')`, which shows the message "Hello, world!".
9+
Ya hemos visto una sentencia, `alert('¡Hola mundo!')`, que muestra el mensaje "¡Hola mundo!".
1010

11-
We can have as many statements in our code as we want. Statements can be separated with a semicolon.
11+
Podemos tener tantas sentencias en nuestro código como queramos, las cuales se pueden separar con un punto y coma.
1212

13-
For example, here we split "Hello World" into two alerts:
13+
Por ejemplo, aquí separamos "Hello World" en dos alerts:
1414

1515
```js run no-beautify
16-
alert('Hello'); alert('World');
16+
alert('Hola'); alert('Mundo');
1717
```
1818

19-
Usually, statements are written on separate lines to make the code more readable:
19+
Generalmente, las sentencias se escriben en líneas separadas para hacer que el código sea más legible:
2020

2121
```js run no-beautify
22-
alert('Hello');
23-
alert('World');
22+
alert('Hola');
23+
alert('Mundo');
2424
```
2525

26-
## Semicolons [#semicolon]
26+
## Punto y coma [#semicolon]
2727

28-
A semicolon may be omitted in most cases when a line break exists.
28+
Se puede omitir un punto y coma en la mayoría de los casos cuando existe un salto de línea.
2929

30-
This would also work:
30+
Esto también funcionaría:
3131

3232
```js run no-beautify
33-
alert('Hello')
34-
alert('World')
33+
alert('Hola')
34+
alert('Mundo')
3535
```
3636

37-
Here, JavaScript interprets the line break as an "implicit" semicolon. This is called an [automatic semicolon insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion).
37+
Aquí, JavaScript interpreta el salto de línea como un punto y coma "implícito". Esto se denomina [inserción automática de punto y coma](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion).
3838

39-
**In most cases, a newline implies a semicolon. But "in most cases" does not mean "always"!**
39+
**En la mayoría de los casos, una nueva línea implica un punto y coma. Pero "en la mayoría de los casos" no significa "siempre"!**
4040

41-
There are cases when a newline does not mean a semicolon. For example:
41+
Hay casos en que una nueva línea no significa un punto y coma. Por ejemplo:
4242

4343
```js run no-beautify
4444
alert(3 +
4545
1
4646
+ 2);
4747
```
4848

49-
The code outputs `6` because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus `"+"`, then it is an "incomplete expression", so the semicolon is not required. And in this case that works as intended.
49+
El código da como resultado `6` porque JavaScript no inserta punto y coma aquí. Es intuitivamente obvio que si la línea termina con un signo más `"+"`, es una "expresión incompleta", por lo que no se requiere el punto y coma. Y en este caso eso funciona según lo previsto.
5050

51-
**But there are situations where JavaScript "fails" to assume a semicolon where it is really needed.**
51+
**Pero hay situaciones en las que JavaScript "falla" al asumir un punto y coma donde realmente se necesita.**
5252

53-
Errors which occur in such cases are quite hard to find and fix.
53+
Los errores que ocurren en tales casos son bastante difíciles de encontrar y corregir.
5454

55-
````smart header="An example of an error"
56-
If you're curious to see a concrete example of such an error, check this code out:
55+
````smart header="Un ejemplo de error"
56+
Si tienes curiosidad por ver un ejemplo concreto de tal error, mira este código:
5757
5858
```js run
5959
[1, 2].forEach(alert)
6060
```
6161
62-
No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later. For now, just remember the result of the code: it shows `1` then `2`.
62+
No es necesario pensar en el significado de los corchetes `[]` y `forEach` todavía, los estudiaremos más adelante. Por ahora, solo recuerda el resultado del código: muestra `1` luego `2`.
6363
64-
Now, let's add an `alert` before the code and *not* finish it with a semicolon:
64+
Ahora, agreguemos un 'alert' antes del código y *no* terminemos con un punto y coma:
6565
6666
```js run no-beautify
67-
alert("There will be an error")
67+
alert("Habrá un error")
6868
6969
[1, 2].forEach(alert)
7070
```
7171
72-
Now if we run the code, only the first `alert` is shown and then we have an error!
72+
Ahora, si ejecutamos el código, ¡solo se muestra el primer `alert` y luego tenemos un error!
7373
74-
But everything is fine again if we add a semicolon after `alert`:
74+
Pero todo está bien nuevamente si agregamos un punto y coma después de `alert`:
7575
```js run
76-
alert("All fine now");
76+
alert("Todo bien ahora");
7777
78-
[1, 2].forEach(alert)
78+
[1, 2].forEach(alert)
7979
```
8080
81-
Now we have the "All fine now" message followed by `1` and `2`.
81+
Ahora tenemos el mensaje "Todo bien ahora" seguido de `1` y `2`.
8282
8383
84-
The error in the no-semicolon variant occurs because JavaScript does not assume a semicolon before square brackets `[...]`.
84+
El error en la variante sin punto y coma se produce porque JavaScript no asume un punto y coma antes de los corchetes `[...]`.
8585
86-
So, because the semicolon is not auto-inserted, the code in the first example is treated as a single statement. Here's how the engine sees it:
86+
Entonces, como el punto y coma no se inserta automáticamente, el código del primer ejemplo se trata como una sola sentencia. Así es como lo ve el motor:
8787
8888
```js run no-beautify
89-
alert("There will be an error")[1, 2].forEach(alert)
89+
alert("Habrá un error")[1, 2].forEach(alert)
9090
```
9191
92-
But it should be two separate statements, not one. Such a merging in this case is just wrong, hence the error. This can happen in other situations.
92+
Pero deberían ser dos sentencias separadas, no una. Tal unión en este caso es simplemente incorrecta, de ahí el error. Esto puede suceder en otras situaciones también.
9393
````
9494

95-
We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer -- especially for a beginner -- to use them.
95+
Recomendamos colocar puntos y coma entre las sentencias, incluso si están separadas por saltos de línea. Esta regla está ampliamente adoptada por la comunidad. Notemos una vez más que es posible omitir los puntos y coma la mayoría del tiempo. Pero es más seguro, especialmente para un principiante, usarlos.
96+
97+
## Comentarios
9698

97-
## Comments
99+
A medida que pasa el tiempo, los programas se vuelven cada vez más complejos. Se hace necesario agregar *comentarios* que describan lo que hace el código y por qué.
98100

99-
As time goes on, programs become more and more complex. It becomes necessary to add *comments* which describe what the code does and why.
101+
Los comentarios se pueden poner en cualquier lugar de un script. No afectan su ejecución porque el motor simplemente los ignora.
100102

101-
Comments can be put into any place of a script. They don't affect its execution because the engine simply ignores them.
102103

103-
**One-line comments start with two forward slash characters `//`.**
104+
**Los comentarios de una línea comienzan con dos caracteres de barra diagonal `//`.**
104105

105-
The rest of the line is a comment. It may occupy a full line of its own or follow a statement.
106+
El resto de la línea es un comentario. Puede ocupar una línea completa propia o seguir una sentencia.
106107

107-
Like here:
108+
Como aqui:
108109
```js run
109-
// This comment occupies a line of its own
110+
// Este comentario ocupa una línea propia.
110111
alert('Hello');
111112

112-
alert('World'); // This comment follows the statement
113+
alert('World'); // Este comentario sigue a la sentencia.
113114
```
114115

115-
**Multiline comments start with a forward slash and an asterisk <code>/&#42;</code> and end with an asterisk and a forward slash <code>&#42;/</code>.**
116+
**Los comentarios de varias líneas comienzan con una barra inclinada y un asterisco <code>/&#42;</code> y terminan con un asterisco y una barra inclinada <code>&#42;/</code>.**
116117

117-
Like this:
118+
Como aquí:
118119

119120
```js run
120-
/* An example with two messages.
121-
This is a multiline comment.
121+
/* Un ejemplo con dos mensajes.
122+
Este es un comentario multilínea.
122123
*/
123-
alert('Hello');
124-
alert('World');
124+
alert('Hola');
125+
alert('Mundo');
125126
```
126127

127-
The content of comments is ignored, so if we put code inside <code>/&#42; ... &#42;/</code>, it won't execute.
128+
El contenido de los comentarios se ignora, por lo que si colocamos el código dentro de <code>/&#42; ... &#42;/</code>, no se ejecutará.
128129

129-
Sometimes it can be handy to temporarily disable a part of code:
130+
A veces puede ser útil deshabilitar temporalmente una parte del código:
130131

131132
```js run
132-
/* Commenting out the code
133-
alert('Hello');
133+
/* Comentando el código
134+
alert('Hola');
134135
*/
135-
alert('World');
136+
alert('Mundo');
136137
```
137138

138-
```smart header="Use hotkeys!"
139-
In most editors, a line of code can be commented out by pressing the `key:Ctrl+/` hotkey for a single-line comment and something like `key:Ctrl+Shift+/` -- for multiline comments (select a piece of code and press the hotkey). For Mac, try `key:Cmd` instead of `key:Ctrl`.
139+
```smart header="¡Usa accesos rápidos del teclado!"
140+
En la mayoría de los editores, se puede comentar una línea de código presionando `key:Ctrl+/` para un comentario de una sola línea y algo como `key:Ctrl+Shift+/` - para comentarios de varias líneas (selecciona una parte del código y pulsa la tecla de acceso rápido). Para Mac, intenta `key: Cmd` en lugar de `key: Ctrl`.
140141
```
141142

142-
````warn header="Nested comments are not supported!"
143-
There may not be `/*...*/` inside another `/*...*/`.
143+
````warn header="¡Los comentarios anidados no son compatibles!"
144+
No puede haber `/*...*/` dentro de otro `/*...*/`.
144145
145-
Such code will die with an error:
146+
Dicho código terminará con un error:
146147
147148
```js run no-beautify
148149
/*
149-
/* nested comment ?!? */
150+
/* comentario anidado ?!? */
150151
*/
151-
alert( 'World' );
152+
alert( 'Mundo' );
152153
```
153154
````
154155

155-
Please, don't hesitate to comment your code.
156+
Por favor, no dudes en comentar tu código.
157+
158+
Los comentarios aumentan el tamaño general del código, pero eso no es un problema en absoluto. Hay muchas herramientas que minimizan el código antes de publicarlo en un servidor de producción. Eliminan los comentarios, por lo que no aparecen en los scripts de trabajo. Por lo tanto, los comentarios no tienen ningún efecto negativo en la producción.
156159

157-
Comments increase the overall code footprint, but that's not a problem at all. There are many tools which minify code before publishing to a production server. They remove comments, so they don't appear in the working scripts. Therefore, comments do not have negative effects on production at all.
160+
Más adelante, en el tutorial, habrá un capítulo <info:coding-style> que también explica cómo escribir mejores comentarios.
158161

159-
Later in the tutorial there will be a chapter <info:code-quality> that also explains how to write better comments.

0 commit comments

Comments
 (0)