Como desarrolladores web, a menudo parece que pasamos más tiempo corrigiendo errores e intentando resolver problemas que escribiendo código. En esta guía, veremos algunas técnicas de depuración comunes, así que vamos a atascarnos.
"No prepararse, prepárese para fallar"
¡Qué mejor manera de comenzar un artículo que con un viejo cliché! Aparecerán errores y problemas. Simplemente no hay forma de escapar de esto (lo siento). Con una planificación simple, hay formas en las que podemos minimizar la complejidad y la cantidad de problemas que enfrentamos.
Divida la tarea en tareas más pequeñas
Ahora, lo entiendo, a todos nos gusta emocionarnos mucho y sumergirnos directamente en nuestros proyectos de codificación. La cuestión es que, sin algún tipo de plan, ¡nos estamos creando problemas incluso antes de comenzar!
Si te dijera "tienes que crear una aplicación de lista de compras" y empezaras a programar de inmediato, ¿qué pasaría? Terminarías mirando un cursor parpadeante preguntándote cómo o qué hacer primero, maldiciendo mi nombre en voz baja por pedirte que hicieras esa tarea.
Siempre es más fácil tomar un problema grande y dividirlo en muchos problemas más pequeños. Por ejemplo, podemos dividir el proyecto de la lista de compras en tareas más pequeñas:
- Cree un formulario para agregar un elemento a la lista
- Permitir que un usuario elimine un elemento de la lista
- Mostrar un número total de elementos en la lista
Incluso puede dividir estas tareas en tareas más detalladas. Por ejemplo, para la primera tarea de nuestra lista, nuestra primera, "pequeña mini tarea" (¿debería registrar ese término?) Podría ser:
1) Cree un campo de entrada para capturar el nombre del artículo
2) Crea un botón que llame a una función addToList()
cuando se hace clic
3) Escriba la lógica dentro de la addToList()
función que agrega el elemento a la lista
Y así. Entiendes la idea. Prefiero dividir el trabajo de esta manera, ya que realmente me hace pensar en los problemas que encontraré temprano y las soluciones (he escrito un artículo en profundidad sobre esto aquí) antes de escribir cualquier código. También me ayuda a entender lo que estoy tratando de hacer y me pone en la "zona". Es mucho más fácil resolver los problemas que surgen cuando comprende lo que está tratando de lograr.
Esté preparado para purgar su código
Para hacer una tortilla, tenemos que romper unos huevos. Esto significa estar preparado para reescribir completamente nuestro código para que funcione.
Apuesto a que estás pensando, "oh hombre, me tomó días / semanas / milenios llegar tan lejos con mi código, ¿y ahora tengo que borrarlo?" Um, sí. A veces. Lo siento. La realidad con el desarrollo web es que el código cambiará todo el tiempo, por varias razones: errores, revisiones de código, cambios en los requisitos, aburrimiento, etc.
A veces nos sentimos tan valiosos con nuestro código y no podemos soportar borrarlo, que intentamos superar los problemas intentando "encajar una clavija redonda en un agujero cuadrado". Pensamos "¡NOO! No puedo eliminar este método. Me tomó una eternidad. ¡Tiene que haber una manera!" Este bloqueo mental causa nuestros propios problemas, porque simplemente reescribiendo lo que tenemos actualmente, podríamos encontrar la solución a nuestros problemas.
Ahora que estamos bien y preparados, veamos qué sucede cuando las cosas salen mal.
Los mensajes de error son buenos
¿Qué es peor que ver un mensaje de error cuando algo sale mal? No ver ningún mensaje de error cuando algo sale mal. Aunque es una sensación desalentadora ver un gran rastro de pila roja cuando ejecutamos nuestro código cuidadosamente elaborado, los mensajes de error están ahí para decir "sí, las cosas están mal ahora, pero aquí hay algunos lugares en los que puede buscar para comenzar a arreglarlo" .
Si echamos un vistazo a este ejemplo:
let animals; function addAnimal(){ animals.push('elephant'); } addAnimal();
Ahora echemos un vistazo al error:
TypeError: Cannot read property 'push' of undefined at addAnimal (//vanilla.csb.app/src/index.js:8:11) at evaluate (//vanilla.csb.app/src/index.js:11:1) at $n (//codesandbox.io/static/js/sandbox.acff3316.js:1:148704)
He omitido parte del rastro de la pila, ya que la mayoría es, bueno, un galimatías. Dependiendo de cómo su proyecto de frontend maneje los mensajes de error, incluso puede ver el error en su navegador:

Las partes importantes del seguimiento de la pila suelen estar en la parte superior: el mensaje, la función y el número de línea, y nuestro navegador también nos muestra esto. Entonces, el intérprete hace lo mejor para decirnos qué está mal. Es una pena que no pueda resolvernos el problema, ¿eh?
Por lo tanto, hemos terminado de tener nuestro ataque de pánico al ver el error y hemos seleccionado información del mensaje de error. Si lo desglosamos, podemos ver esta línea:
Cannot read property 'push' of undefined
Esto generalmente significa que hay una variable no definida o inicializada en algún lugar. ¿¡¿PERO DONDE?!?
Si continuamos leyendo el seguimiento de la pila, vemos que el error ocurre dentro de la addAnimal()
función. Podemos ver que estamos tratando de introducir un nuevo animal en una matriz, ¡ah! Olvidé inicializar la animals
matriz. Doh! Nuestro código fijo se ve así:
let animals = []; function addAnimal() { animals.push("elephant"); } addAnimal();
El error arrojado en el navegador le mostrará el problema más rápido, pero no todos los proyectos frontend estarán configurados para hacer esto, y los desarrolladores backend no tienen este lujo. Es por eso que recomiendo aprender a leer el seguimiento de la pila.
Para vencer al error, debes pensar como el error.
El seguimiento de la pila le da una idea de cuál es el error. Bueno, a veces lo hace y a veces no. ¿Qué sucede si ve un mensaje de error que se parece más a glifos de cueva que a inglés? ¿O qué pasa si no hay ningún error, pero su código simplemente no actúa como pensaba?
Es hora de sacar el depurador. Veamos otro ejemplo. ¡Pero primero algo de contexto!
El Sr. Bob CEO (¿quién es un CEO, quién lo hubiera pensado?) Se acerca a usted y le dice
"Oye, tengo una idea increíble para un producto.
- Quiero una aplicación web que le permita al usuario ingresar un número.
- Si el número es menor que 5, el mensaje debe leer "BAJO".
- Si el número es igual o superior a 5, el mensaje debe leer "OVER".
Esta es una idea de un millón de dólares y quiero que me la construyas ".
"¡BUENO!" Dices, y te pones a trabajar.
* Montaje de codificación con música dramática que se reproduce a medida que avanza el tiempo *
Ha completado el código para su aplicación web. ¡Hurra!
My super awesome number app Submit 0
(function () { const numberInputSubmitButton = document.getElementById("number-input-submit-button") numberInputSubmitButton.addEventListener("click", function () { const numberInputValue = document.getElementById("number-input").value; let text; if(numberInputValue > 5) { text = "OVER"; } else { text = "UNDER"; } document.getElementById("number-display").innerHTML = text }); })();
(Nota: Es posible que ya haya detectado el error. Si lo hizo, hagamos como si no lo hizo. Si no ha notado el error, está bien).
Es hora de empezar a probar. Repasemos algunos casos de uso para nuestra lógica empresarial.
1) El usuario ingresa 3:

2) El usuario ingresa 7

¡Hasta aquí todo bien! Pero, ¿qué pasa si ingresamos 5?

OH NO! A bug! The text displayed is incorrect, it should display "OVER" but instead displays "UNDER". Hmm, no error messages,and I can't seem to see in the code what is wrong. Let's run the debugger and step through the code.
Using the debugger

A good place to start is to put a breakpoint as close to the buggy code as possible. You can determine this by reading the code, error messages, or if you have that "ah-ha!I know which method is causing this" moment. From here, it's a case of stepping through the code, inspecting the variables, and checking if the correct code branches are run.
In our example, I have put a breakpoint at the start of my if statement
- as this is where the failing logic is.
Once I start debugging, chrome opens and I can replicate the issue by entering "5" and clicking submit. This hits the breakpoint, and immediately there are a few things to note:
- The debugger stops at the breakpoint, so this means I'm on the right track
- This also means that the function is being called correctly, and event handlers are working as expected
- I can also see that the user input is being captured correctly (from the "variables" panel on the left-hand side, I can see that "5" was entered)
So far so good, no immediate issues to worry about. Well, code related ones anyway. Next, I'll press F10 to step through the code. This runs each statement individually, allowing us to inspect elements, variables, and other things at our own pace. Isn't technology just fabulous?
Remember since I expect the message "OVER" to appear when the user enters "5", I'm expecting the debugger to take me into the first branch of the if statement...

BUT NO! I'm brought into the second branch. Why? I need to amend the conditional to read "more than or equals to" as opposed to "more than".
if(numberInputValue >= 5) { text = "OVER"; } else { text = "UNDER"; }
Success! Our bug is fixed. Hopefully this gives you an idea on how to walk through the code, making use of VSCodes awesome debugging tools.
More Debugging tips
- If your breakpoints aren't being hit, this could be part of the issue. Make sure the correct functions or event handlers are being called in the way you expect
- You can
step over
functions you want to skip. If you want to debug any functions you come across, use thestep into
command - Watch out for variables, parameters, and arguments as you are stepping through your code. Are the values what you expect?
- Write code in a way that is easier to read/debug. It might look cool to have your code on one line, but it makes debugging harder
Google is your friend
Ok so we've looked at the stack-trace, tried debugging, and we're still stuck with this bug. The only thing left to do now is make a sacrifice to the coding gods and hope things fix themselves!
Or I guess we could use Google.
Google is a treasure trove of software development problems and solutions, all at our fingertips. It can be sneakily difficult to access this information though, as you have to know how to Google the right things to get the right information! So how do we effectively use Google?
Let's look back to our first example - you've read the stack trace, looked at the code, but the message Cannot read property 'push' of undefined
is still driving you mad. Bewildered, you take to Google in hopes of finding an answer. Here are some things to try:
Copy and paste the error message. Sometimes this works, depending on how "generic" the error message is. For example, if you get a Null pointer exception (who doesn't love those?), Googling "Null pointer exception" might not return very helpful results.
Search for what you are trying to do. For example, "How to create an array and add an item to the end". You might find some generous developer has posted a solution using best practices on StackOverflow, for example. You might also find this solution is completely different from yours - remember what I said about being comfortable purging your code?
A side note on using someone else's code - try and avoid blindly copying and pasting, make sure you understand what the code does first!
Ask for help the right way
Hopefully, after a mix of debugging, stack trace investigating, and Googling you have seen the light at the end of the tunnel and solved your problem. Unfortunately, depending on what you are trying to do, you still might be a bit stumped. This is a good time to seek advice from other people.
Now, before you run into the street screaming "my code is broken please help me!", it's important to know the best way to ask for help. Asking for help in the right way makes it easier for people to understand the problem and help you solve it. Let's look at some examples:
Bad - "My code is broken and I don't know what's wrong."
Good - "I'm trying to add an item to the end of an array in JavaScript, and I'm getting this error message: Cannot read property 'push' of undefined. Here's my code so far."
See how the "Good" example is much more informative? More information makes it easier for other kindhearted devs to help you out. This is a good habit to get into as it not only benefits you when you are learning to code but also in your first job when you need to ask for help.
So where can you ask for help?
- StackOverflow
- Slack groups
- Colleagues or developer friends
Quick Tip: You can use a tool like CodeSandbox.io or CodePen.io to recreate your problem and share it with people.
Practice, practice, practice
Just like Rome wasn't built in a day (well, it could have been for all I know) you will not become king bug squasher overnight. As your career goes on and your experience grows, you'll be armed with a wealth of knowledge that helps you solve bugs and issues faster. I regularly find myself saying "ah, I've solved that before" or "oh yeah, I have a StackOverflow link that helps me here" and the whole thing becomes a lot easier. So keep practicing, and this skill will grow naturally.
Thanks for reading! If you enjoyed this article, why not subscribe to my newsletter?
Every week I send out a list of 10 things I think are worth sharing — my latest articles, tutorials, tips and interesting links for upcoming developers like you. I also give out some free stuff from time to time :)