Debugging JavaScript code for beginners: Tips and tricks for finding and fixing errors

Oladipupo Ishola
9 min readApr 21, 2023

--

Image by
Arnab Roy Chowdhury

Debugging is a necessary skill for any developer, but it is especially important for JavaScript developers. JavaScript is a dynamic and flexible language, but it can also be tricky to debug due to its loosely typed nature and the fact that it’s often run in the browser.

In this article, we'll look at some of the most common JavaScript errors and provide techniques and tools for debugging them. We'll also go over some best practices for becoming a better debugger.

By the end of this article, you'll have a solid understanding of the tools and techniques required to effectively and efficiently debug your JavaScript code.

Let's start with some common errors that may occur while coding the next Silicon Valley application or perhaps the next AI that will take our jobs and send us all back to farming lol.

Common Errors

JavaScript is a programming language that enables programmers to create complex and dynamic web applications. However, with this flexibility comes the possibility of making mistakes. Here are some of the most common errors encountered by JavaScript developers:

A. Syntax Errors

Syntax errors occur when your code does not adhere to the JavaScript syntax rules. Here are some examples of syntax errors:

// Missing parentheses
if x === 5 {
console.log("x is equal to 5");
}

// Misspelled keyword
for(let i = 0; i < 5; i++ {
console.log(i);
}

// Using the wrong operator
let x = 10;
if (x = 5) {
console.log("x is equal to 5");
}

To debug syntax errors, carefully review your code for any syntax errors that may be causing the issue. You can also use linters and code editors to detect syntax errors before running your code.

B. Runtime Errors

Runtime errors occur when your code attempts to perform an action that is not possible. Some examples of runtime errors are:

// Dividing by zero
let x = 10;
let y = 0;
let z = x / y;

// Calling a function that doesn't exist
let result = someFunction();

// Using an undefined variable
let x;
let y = x + 5;

To debug runtime errors, use the browser developer tools to locate the line of code that is causing the problem. You can also include console.log statements in your code to assist you in identifying the problem.

C. Logic Errors

Logic errors occur when your code executes without error but produces an unexpected result. Here are some examples of logic mistakes:

// Infinite loop
let x = 0;
while (x < 10) {
console.log(x);
}

// Using the wrong comparison operator
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
}

// Using the wrong variable
let x = 10;
let y = 5;
let z = x * y;
console.log("The product is: " + x);

To debug logic errors, carefully review your code and consider the logic you've written. You can also use tools like console.log statements and breakpoints to help you pinpoint the source of the problem.

Tools for Debugging JavaScript

When it comes to debugging JavaScript, there are numerous tools available to assist you in identifying and correcting errors in your code. Here are a few of the most frequently used tools:

A. Browser Developer Tools

Most modern web browsers include built-in developer tools for inspecting and debugging JavaScript code. These tools typically include a console for displaying error messages and running JavaScript commands, as well as a debugger for stepping through your code line by line and identifying where errors are occurring.

In Google Chrome, for example, you can access the developer tools by right-clicking on a web page and selecting "Inspect." After opening the developer tools, navigate to the "Console" and "Sources" tabs to access the console and debugger, respectively.

B. Linters

Linters are tools that examine your code for potential errors and issues with code style. They can be used to detect syntax errors before running your code and to identify areas of your code that may be difficult to read or maintain.

ESLint, for example, is a popular JavaScript linter that can be integrated into your development workflow. It can be set to enforce various coding styles and best practices, such as requiring semicolons at the end of statements or prohibiting the use of certain global variables.

C. Code Editors

Debugging tools are built into many code editors, allowing you to set breakpoints, inspect variables, and step through your code line by line. These tools can be extremely useful for detecting and correcting errors in your code.

Visual Studio Code, for example, is a popular code editor that includes a robust set of debugging tools. You can use it to set breakpoints, step through code, and inspect variables in real-time.

D. Console.log

Adding console.log statements throughout your code is sometimes the simplest way to debug it. These statements enable you to print the value of a variable or the result of a function call to the console, allowing you to see what's going on in your code in real-time.

For instance, if you're attempting to debug a function that isn't returning the expected value, you could add a console.log statement to output the value of a variable within the function:

function myFunction(x, y) {
let result = x + y;
console.log("The result is: " + result);
return result;
}

myFunction(2, 3); // Outputs "The result is: 5" to the console

You can quickly identify and fix errors in your JavaScript code by using these tools, making your development process more efficient and effective.

Debugging Techniques

Debugging JavaScript code can be a difficult and time-consuming task, particularly for beginners. Here are some debugging techniques to help you more efficiently identify and fix errors in your code:

A. Start with the console

The console is a powerful tool for displaying error messages, logging values, and running code on the fly. When you find an error in your code, check the console for any error messages that may provide information about the problem.

Example:

function calculateArea(width, height) {
if (typeof width !== 'number' || typeof height !== 'number') {
console.error('Invalid arguments: width and height must be numbers.');
return null;
}

return width * height;
}

calculateArea('a', 5);

In this example, we’re passing a string ("a") instead of a number to the calculateArea()function. We can see an error message in the console that says, "Invalid arguments: width and height must be numbers." This provides us with information about the problem and allows us to correct it.

B. Breakpoints

Breakpoints are markers in your code that you can use to halt execution at a specific line or function. This allows you to inspect the current state of your code and variables.

Simply click on the line number in your code editor or debugger to set a breakpoint.

Example:

function calculateArea(width, height) {
debugger;

if (typeof width !== 'number' || typeof height !== 'number') {
console.error('Invalid arguments: width and height must be numbers.');
return null;
}

return width * height;
}

calculateArea(10, 5);

We've added a "debugger" statement to the calculateArea() function in this example. This places a breakpoint at that line, halting execution. When we run the code, the debugger will come to a halt at the "debugger" statement, allowing us to inspect the state of our code and variables.

C. Step through the code

Stepping through code allows you to run your code one line at a time, which can help you find errors in your code. This can be accomplished by utilizing the debugger tools in your browser or code editor.

Example:

function calculateArea(width, height) {
debugger;

if (typeof width !== 'number' || typeof height !== 'number') {
console.error('Invalid arguments: width and height must be numbers.');
return null;
}

return width * height;
}

calculateArea(10, 5);

We've added a "debugger" statement to the "calculateArea()" function in this example. When we run the code and reach the breakpoint, we can use the debugger tools to step through the code one line at a time, inspecting our code and variables as we go.

D. Inspect variables

Inspecting variables allows you to see a variable's current state at a specific point in time. This can be useful in identifying problems with variable assignments or logic errors.

Simply hover your mouse over a variable to inspect it, or use the debugger tools in your browser or code editor.

Example:

function calculateArea(width, height) {
debugger;

if (typeof width !== 'number' || typeof height !== 'number') {
console.error('Invalid arguments: width and height must be numbers.');
return null;
}

const area = width * height;
console.log('Area:', area);

return area;
}

calculateArea(10, 5);

E. Use console.trace()

To obtain a stack trace, follow these steps: It can be difficult to pinpoint the source of an error at times. You can see the call stack that resulted in the error by using console.trace(). This is especially useful when working with large codebases or libraries.

Example:

function a() {
b();
}

function b() {
c();
}

function c() {
console.trace();
}

a();

This will generate a stack trace that shows the order of function calls:

console.trace @ VM62:7
c @ VM62:9
b @ VM62:4
a @ VM62:1
(anonymous) @ VM63:9

F. Use breakpoints in your browser’s developer tools:

Most modern browsers include built-in developer tools for setting breakpoints in your code. This allows you to pause code execution at a specific point and inspect variable values at that point. You can walk through your code line by line and see what happens at each step.

In Google Chrome, for example, you can create a breakpoint by clicking on the line number where you want to pause execution. When your code reaches that point, it will pause, allowing you to inspect the values of variables.

G. Use a linter to catch common errors:

A linter is a program that analyzes your code and checks for common errors such as syntax errors and the use of undeclared variables. You can save yourself a lot of time and frustration if you catch these errors early.

ESLint, for example, is a popular JavaScript linter that can be integrated into your code editor or build process. It is capable of detecting a wide range of errors and potential issues, as well as enforcing coding standards and best practices.

These are just a few of the debugging techniques available to you as a JavaScript developer. By mastering these techniques, you will be able to track down and fix errors in your code more quickly and efficiently.

Best Practices for Debugging

The following are some best practices for debugging JavaScript code:

  1. Use descriptive variable and function names: Using descriptive variable and function names can help your code be easier to read and understand. When debugging, it can also help you spot errors and locate the source of a problem.
  2. Break complex code into smaller, testable pieces: It can be difficult to track down errors when working with a large, complex codebase. You can isolate and debug problems more easily if you break your code down into smaller, testable pieces.
  3. Create unit and integration tests for your code to help you catch errors early and ensure that your code works as expected. You can run your tests after making changes to your code to ensure that nothing has broken.
  4. Use version control: Version control systems such as Git can help you keep track of changes to your code and easily revert to previous versions if something goes wrong.
  5. Don't be afraid to ask for assistance: Debugging can be frustrating, and it can sometimes be beneficial to get a fresh perspective. Contact other developers, participate in online communities, or look for resources such as documentation or tutorials.
  6. Use console.log() statements wisely: Console.log() statements are an effective debugging tool, but they can also clog up your code and make it difficult to read. Use them strategically to output specific values or messages that can aid in the identification of problems.

You can make debugging easier and more effective by following these best practices, and you can catch errors before they cause problems for your users.

Conclusion

To summarize, debugging is an essential part of the software development process, and JavaScript developers must be able to effectively debug their code. While tracking down errors can be frustrating, with the right tools, techniques, and best practices, you can streamline the debugging process and catch errors before they impact your users.

You can make debugging easier and more efficient by being aware of common errors, using the right tools, breaking down complex code into smaller, testable pieces, and adhering to best practices. Remember to be patient, persistent, and willing to ask for help when you need it, and you'll be well on your way to mastering JavaScript code debugging.

--

--

Oladipupo Ishola
Oladipupo Ishola

Written by Oladipupo Ishola

Tech Writer | Full Stack Developer | Frontend Developer | Backend Developer | Co-Building @techverseacademy | Mentor & Code Instructor | MLH ’21 Alum

No responses yet