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
Before writing more complex code, let's talk about debugging.
3
+
Antes de escribir código más complejo, hablemos de debugging.
4
4
5
-
[Debugging](https://en.wikipedia.org/wiki/Debugging) is the process of finding and fixing errors within a script. All modern browsers and most other environments support debugging tools -- a special UI in developer tools that makes debugging much easier. It also allows to trace the code step by step to see what exactly is going on.
5
+
Todos lo exploradores modernos y la mayoría de los otros ambientes soportan el "debugging" -- una herramienta especial de UI para desarrolladores que nos permite encontrar y reparar errores más fácilmente.
6
6
7
-
We'll be using Chrome here, because it has enough features, most other browsers have a similar process.
7
+
Aquí utilizaremos Chrome porque es uno de los que mejores herramientas tienen en este aspecto.
8
8
9
-
## The "Sources" panel
9
+
## El panel "sources/recursos"
10
10
11
-
Your Chrome version may look a little bit different, but it still should be obvious what's there.
11
+
Tu version de Chrome posiblemente se vea distinta, pero sigue siendo obvio lo que hablamos aquí.
12
12
13
-
-Open the [example page](debugging/index.html)in Chrome.
14
-
-Turn on developer tools with`key:F12` (Mac: `key:Cmd+Opt+I`).
15
-
-Select the `Sources` panel.
13
+
-Abre la [pagina de ejemplo](debugging/index.html)en Chrome.
14
+
-Activa las herramientas de desarrollo con`key:F12` (Mac: `key:Cmd+Opt+I`).
15
+
-Selecciona el panel `sources/recursos`.
16
16
17
-
Here's what you should see if you are doing it for the first time:
17
+
Esto es lo que debería ver si lo está haciendo por primera vez:
18
18
19
19

20
20
21
-
The toggler button <spanclass="devtools"style="background-position:-172px-98px"></span> opens the tab with files.
21
+
El botón botón de activación (toggle button) <spanclass="devtools"style="background-position:-168px-76px"></span> abre la pestaña con los archivos.
22
22
23
-
Let's click it and select `hello.js`in the tree view. Here's what should show up:
23
+
Hagamos click allí y seleccionemos `index.html` y luego `hello.js`en el árbol de archivos. Esto es lo que se debería ver:
24
24
25
25

26
26
27
-
The Sources panel has 3 parts:
27
+
Podemos ver tres zonas:
28
28
29
-
1.The**File Navigator**pane lists HTML, JavaScript, CSS and other files, including images that are attached to the page. Chrome extensions may appear here too.
30
-
2.The**Code Editor**pane shows the source code.
31
-
3.The **JavaScript Debugging**pane is for debugging, we'll explore it soon.
29
+
1.La**Zona de recursos**lista los archivos HTML, JavaScript, CSS y otros, incluyendo imágenes que están incluidas en la página. Las extensiones de Chrome quizás también aparezcan aquí.
30
+
2.La**Zona de Recursos**muestra el código fuente de los archivos.
31
+
3.La **Zona de información y control**es para "debugging", la exploraremos pronto.
32
32
33
-
Now you could click the same toggler <spanclass="devtools"style="background-position:-172px-122px"></span> again to hide the resources list and give the code some space.
33
+
Ahora puedes hacer click en el mismo botón de activación <spanclass="devtools"style="background-position:-200px-76px"></span> otra vez para esconder la lista de recursos y darnos más espacio.
34
34
35
-
## Console
35
+
## Consola
36
36
37
-
If we press `key:Esc`, then a console opens below. We can type commands there and press `key:Enter`to execute.
37
+
Si presionamos `Esc`, la consola se abrirá debajo. Podemos escribir los comandos y presionar `key:Enter`para ejecutar.
38
38
39
-
After a statement is executed, its result is shown below.
39
+
Después de que se ejecuta una sentencia, el resultado se muestra debajo.
40
40
41
-
For example, here `1+2`results in `3`, and`hello("debugger")`returns nothing, so the result is`undefined`:
41
+
Por ejemplo, si colocamos `1+2`el resultado es `3`, y`hello("debugger")`no devuelve nada, entonces el resultado es`undefined`:
42
42
43
43

44
44
45
-
## Breakpoints
45
+
## Breakpoints (puntos de interrupción)
46
46
47
-
Let's examine what's going on within the code of the [example page](debugging/index.html). In`hello.js`, click at line number `4`. Yes, right on the`4` digit, not on the code.
47
+
Examinemos qué pasa con el código de la [página de ejemplo](debugging/index.html). En`hello.js`, haz click en el número de línea `4`. Si, en el número`4`, no en el código.
48
48
49
-
Congratulations! You've set a breakpoint. Please also click on the number for line`8`.
49
+
¡Felicidades! Ya configuraste un breakpoint. Por favor haz click también en el número de la linea`8`.
50
50
51
-
It should look like this (blue is where you should click):
51
+
Debería verse así (en donde está azul es donde deberías hacer click):
52
52
53
53

54
54
55
-
A*breakpoint*is a point of code where the debugger will automatically pause the JavaScript execution.
55
+
Un*breakpoint*es un punto de código donde el debugger pausará automáticamente la ejecución de JavaScript.
56
56
57
-
While the code is paused, we can examine current variables, execute commands in the console etc. In other words, we can debug it.
57
+
Mientras se pausa el código, podemos examinar las variables actuales, ejecutar comandos en la consola, etc. En otras palabras, podemos depurar.
58
58
59
-
We can always find a list of breakpoints in the right panel. That's useful when we have many breakpoints in various files. It allows us to:
60
-
-Quickly jump to the breakpoint in the code (by clicking on it in the right panel).
61
-
-Temporarily disable the breakpoint by unchecking it.
62
-
-Remove the breakpoint by right-clicking and selecting Remove.
63
-
- ...And so on.
59
+
Siempre podemos encontrar una lista de los breakpoints en el panel derecho. Esto es muy útil cuando tenemos muchos breakpoints en varios archivos. Ya que nos permite:
60
+
-Saltar rápidamente al breakpoint en el código (haciendo click en él dentro del panel).
61
+
-Desactivar temporalmente el breakpoint desmarcándolo.
62
+
-Eliminar el breakpoint haciendo click derecho y seleccionando quitar/eliminar/remove.
63
+
- ...y mucho más.
64
64
65
-
```smart header="Conditional breakpoints"
66
-
*Right click* on the line number allows to create a *conditional* breakpoint. It only triggers when the given expression is truthy.
65
+
```smart header="Breakpoints Condicionales"
66
+
*Click derecho* en el número de línea nos permite crear un breakpoint *concional*. Solo se ejecutará cuando la expresión sea verdadera.
67
67
68
-
That's handy when we need to stop only for a certain variable value or for certain function parameters.
68
+
Esto es útil cuando necesitamos detener la ejecución para cierto valor de variable o para ciertos párametros de función.
69
69
```
70
70
71
-
## Debugger command
71
+
## Comando debugger
72
72
73
-
We can also pause the code by using the `debugger` command in it, like this:
73
+
También podemos pausar el código utilizando el comando `debugger`, así:
74
74
75
75
```js
76
76
functionhello(name) {
@@ -84,113 +84,100 @@ function hello(name) {
84
84
}
85
85
```
86
86
87
-
That's very convenient when we are in a code editor and don't want to switch to the browser and look up the script in developer tools to set the breakpoint.
87
+
Esto es muy conveniente cuando estamos en un editor de código. No necesitamos cambiar al explorador y revisar el script en la consola de desarrolladores para setear el breakpoint.
88
88
89
89
90
-
## Pause and look around
90
+
## Pausar y mirar alrededor
91
91
92
-
In our example, `hello()`is called during the page load, so the easiest way to activate the debugger (after we've set the breakpoints) is to reload the page. So let's press `key:F5` (Windows, Linux) or`key:Cmd+R` (Mac).
92
+
En nuestro ejemplo, `hello()`se llama durante la carga de la página, entonces la forma mas fácil de activar el debugger es recargando la página. Entonces presionemos `key:F5` (en Windows ó Linux) ó`key:Cmd+R` (en Mac).
93
93
94
-
As the breakpoint is set, the execution pauses at the 4th line:
94
+
Como el breakpoint está definido, la ejecución se detiene en la línea 4:
95
95
96
96

97
97
98
-
Please open the informational dropdowns to the right (labeled with arrows). They allow you to examine the current code state:
98
+
Por favor abre el desplegable de informacion de la derecha (etiquetado con flechas). Este nos permite examinar el estado del código actual:
99
99
100
-
1.**`Watch` -- shows current values for any expressions.**
100
+
1.**`Watch` -- muestra el valor actual de cualquier expresión.**
101
101
102
-
You can click the plus `+`and input an expression. The debugger will show its value at any moment, automatically recalculating it in the process of execution.
102
+
Puedes hacer click en el màs `+`y agregar una expresión. El debugger mostrará su valor en cualquier momento, y se recalcurará automáticamente en el proceso de ejecución.
103
103
104
-
2.**`Call Stack` -- shows the nested calls chain.**
104
+
2.**`Call Stack` -- muestra las llamadas anidadas en la cadena.**
105
105
106
-
At the current moment the debugger is inside `hello()` call, called by a script in`index.html` (no function there, so it's called "anonymous").
106
+
En el momento actual el debugger está dentro de la función `hello()`, llamada por un script en`index.html` (no dentro de ninguna función, por lo que se llama "anonymous").
107
107
108
-
If you click on a stack item (e.g. "anonymous"), the debugger jumps to the corresponding code, and all its variables can be examined as well.
109
-
3.**`Scope` -- current variables.**
108
+
Si haces click en un elemento de la pila, el debugger saltará al código correspondiente, y todas sus variables también serán examinadas.
109
+
3.**`Scope` -- variables activas.**
110
110
111
-
`Local`shows local function variables. You can also see their values highlighted right over the source.
111
+
`Local`muestra las variables de la función local. También puedes ver sus valores resaltados sobre el código fuente.
112
112
113
-
`Global`has global variables (out of any functions).
113
+
`Global`contiene las variables globales (fuera de cualquier función).
114
114
115
-
There's also `this`keyword there that we didn't study yet, but we'll do that soon.
115
+
Tambien tenemos la palabra `this`la cual no estudiaremos ahora, pero pronto lo haremos.
116
116
117
-
## Tracing the execution
117
+
## Tazado de la ejecución
118
118
119
-
Now it's time to *trace* the script.
119
+
Ahora es tiempo de *trazar* el script.
120
120
121
-
There are buttons for it at the top of the right panel. Let's engage them.
<spanclass="devtools"style="background-position:-146px-168px"></span> -- "Resume": continue the execution, hotkey `key:F8`.
124
-
: Resumes the execution. If there are no additional breakpoints, then the execution just continues and the debugger loses control.
121
+
Hay botones para esto en le panel superior derecho. Revisémoslos.
125
122
126
-
Here's what we can see after a click on it:
123
+
<spanclass="devtools"style="background-position:-7px-76px"></span> -- continuar la ejecución, hotkey `key:F8`.
124
+
: Reanudar la ejecución. Si no hay breakpoints adicionales, entonces la ejecución continúa y el debugger pierde el control.
127
125
128
-

129
-
130
-
The execution has resumed, reached another breakpoint inside `say()` and paused there. Take a look at the "Call Stack" at the right. It has increased by one more call. We're inside `say()` now.
131
-
132
-
<spanclass="devtools"style="background-position:-200px-190px"></span> -- "Step": run the next command, hotkey `key:F9`.
133
-
: Run the next statement. If we click it now, `alert` will be shown.
134
-
135
-
Clicking this again and again will step through all script statements one by one.
126
+
Esto es lo que podemos ver al hacer click:
136
127
137
-
<spanclass="devtools"style="background-position:-62px-192px"></span> -- "Step over": run the next command, but *don't go into a function*, hotkey `key:F10`.
138
-
: Similar to the previous the "Step" command, but behaves differently if the next statement is a function call. That is: not a built-in, like `alert`, but a function of our own.
139
-
140
-
The "Step" command goes into it and pauses the execution at its first line, while "Step over" executes the nested function call invisibly, skipping the function internals.
141
-
142
-
The execution is then paused immediately after that function.
128
+

143
129
144
-
That's good if we're not interested to see what happens inside the function call.
130
+
La ejecución continuó, alcanzando el siguiente breakpoint dentro de `say()` y pausándose allí. Revisa el "Call stack" a la derecha. Ha incrementado su valor una llamada. Ahora estamos dentro de `say()`.
: That's similar to "Step", but behaves differently in case of asynchronous function calls. If you're only starting to learn JavaScript, then you can ignore the difference, as we don't have asynchronous calls yet.
132
+
<spanclass="devtools"style="background-position:-137px-76px"></span> -- siguiente paso (corre el comando siguiente), pero *no te metas en la función*, hotkey `key:F10`.
133
+
: Si hacemos click , se mostrará el `alert`. Lo importante es que ese `alert` puede ser cualquier función, la ejecución "se para sobre ella", saltándose los pasos internos.
148
134
149
-
For the future, just note that "Step" command ignores async actions, such as `setTimeout` (scheduled function call), that execute later. The "Step into" goes into their code, waiting for them if necessary. See [DevTools manual](https://developers.google.com/web/updates/2018/01/devtools#async) for more details.
: Es lo mismo que la anterior, pero "Entras" en las funciones anidadas. Haciendo click en este caminarás por todos los pasos uno por uno.
150
137
151
-
<spanclass="devtools"style="background-position:-32px-194px"></span> -- "Step out": continue the execution till the end of the current function, hotkey `key:Shift+F11`.
152
-
: Continue the execution and stop it at the very last line of the current function. That's handy when we accidentally entered a nested call using <spanclass="devtools"style="background-position:-200px-190px"></span>, but it does not interest us, and we want to continue to its end as soon as possible.
138
+
<spanclass="devtools"style="background-position:-104px-76px"></span> -- continuar la ejecución hasta el final de la función actual, hotkey `key:Shift+F11`.
139
+
: La ejecucion se detendrá en la última línea de la función actual. Esto es útil cuando accidentalmente entramos en una llamada anidada usando <spanclass="devtools"style="background-position:-72px-76px"></span>, pero esto no nos interesa, y queremos continuar hasta el final tan rápido como se pueda.
153
140
154
-
<spanclass="devtools"style="background-position:-61px-74px"></span> -- enable/disable all breakpoints.
155
-
: That button does not move the execution. Just a mass on/off for breakpoints.
141
+
<spanclass="devtools"style="background-position:-7px-28px"></span> -- activar/desactivar todos los breakpoints.
142
+
: Este botón no mueve la ejecución. Solo prende y apaga los breakpoints.
156
143
157
-
<spanclass="devtools"style="background-position:-90px-146px"></span> -- enable/disable automatic pause in case of an error.
158
-
: When enabled, and the developer tools is open, a script error automatically pauses the execution. Then we can analyze variables to see what went wrong. So if our script dies with an error, we can open debugger, enable this option and reload the page to see where it dies and what's the context at that moment.
144
+
<spanclass="devtools"style="background-position:-264px-4px"></span> -- activar/desactivar pausa automática en caso de error.
145
+
: Cuando está activo y la consola de developers tools esta abierta, un error de script automáticamente pausa la ejecución. Entonces podemos analizar las variables para ver qué está mal. Y si nuestro script muere por un error, podemos abrir el debugger, activar esta opción y recargar la página para ver dónde muere y cuál es el contexto en ese momento.
159
146
160
-
```smart header="Continue to here"
161
-
Right click on a line of code opens the context menu with a great option called "Continue to here".
147
+
```smart header="Continuar hasta aquí"
148
+
Click derecho en un una línea de código abre el menú contextual con una gran opción que dice "Continua hasta aquí".
162
149
163
-
That's handy when we want to move multiple steps forward to the line, but we're too lazy to set a breakpoint.
150
+
Esto es útil cuando queremos movernos múltiples pasos adelante, pero somos muy flojos como para definir un breakpoint.
164
151
```
165
152
166
153
## Logging
167
154
168
-
To output something to console from our code, there's`console.log` function.
155
+
Para escribir algo en la consola, existe la función`console.log`.
169
156
170
-
For instance, this outputs values from `0`to `4`to console:
157
+
Por ejemplo, esto muestra los valores desde el `0`hasta el `4`en la consola:
171
158
172
159
```js run
173
160
// open console to see
174
161
for (let i =0; i <5; i++) {
175
162
console.log("value,", i);
176
163
}
177
164
```
165
+
Los usuarios regulares no ven este output, ya que está en la consola. Para verlo, debemos abrir la consola de desarrolladores y presionar la tecla `key:Esc` y en otro tab: se abrirá la consola debajo.
178
166
179
-
Regular users don't see that output, it is in the console. To see it, either open the Console panel of developer tools or press `key:Esc` while in another panel: that opens the console at the bottom.
180
167
181
-
If we have enough logging in our code, then we can see what's going on from the records, without the debugger.
168
+
Si tenemos suficiente log en nuestro código, podemos entonces ver lo que va pasando en nuestro registro, sin el debugger.
182
169
183
-
## Summary
170
+
## Resumen
184
171
185
-
As we can see, there are three main ways to pause a script:
186
-
1.A breakpoint.
187
-
2.The `debugger` statements.
188
-
3.An error (if dev tools are open and the button <spanclass="devtools"style="background-position:-90px-146px"></span> is "on").
172
+
Como podemos ver, hay tres formas principales para pausar un script:
173
+
1.Un breakpoint.
174
+
2.La declaración `debugger`.
175
+
3.Un error (Si la consola esta abierta y el botón <spanclass="devtools"style="background-position:-264px-4px"></span> esta "activo").
189
176
190
-
When paused, we can debug - examine variables and trace the code to see where the execution goes wrong.
177
+
Entonces podemos examinar las variables y paso a paso ver qué falla en el proceso de ejecución.
191
178
192
-
There are many more options in developer tools than covered here. The full manual is at<https://developers.google.com/web/tools/chrome-devtools>.
179
+
Hay muchas más opciones en la consola de desarrollo que las que se cubren aquí. El manual completo lo conseguimos en<https://developers.google.com/web/tools/chrome-devtools>.
193
180
194
-
The information from this chapter is enough to begin debugging, but later, especially if you do a lot of browser stuff, please go there and look through more advanced capabilities of developer tools.
181
+
La información de este capítulo es suficiente para debuggear, pero luego, especialmente si hacemos muchas cosas con el explorador, por favor revisa las capacidades avanzadas de la consola de desarrolladores.
195
182
196
-
Oh, and also you can click at various places of dev tools and just see what's showing up. That's probably the fastest route to learn dev tools. Don't forget about the right click and context menus!
183
+
Ah, y también puedes hacer click en todos lados en la consola a ver qué pasa. Esta es probablemente la ruta más rapida para aprender a usar la consola de desarrolladores. ¡Tampoco olvides el click derecho!
0 commit comments