DEV Community

Cover image for 🧩🪰 Practical Debugging Guide: The Art of Solving Frontend Problems
João Victor
João Victor

Posted on

🧩🪰 Practical Debugging Guide: The Art of Solving Frontend Problems

Welcome to our post on "Practical Debugging Guide: The Art of Solving Frontend Problems"! In this article, we will explore the essential aspects of frontend development, focusing on debugging techniques, coding best practices, and ensuring application security. We will provide a tutorial on using Google Chrome DevTools—an indispensable tool for debugging, performance analysis, and web application optimization. This guide is designed to be a valuable resource for both beginners and experienced developers, helping you efficiently identify and resolve issues in your frontend projects. By mastering these techniques, you'll enhance your ability to deliver high-quality, secure, and sustainable code. For more insights and to explore my other repositories or access this post in Portuguese, be sure to visit my GitHub profile at my GitHub.

1. Why It's Critical to Master Debugging, Especially in Legacy Code

Effective debugging of legacy code is essential for maintaining system integrity and preventing regressions. It enables developers to trace and resolve complex issues embedded in the existing codebase, ensuring that new implementations do not introduce conflicts or errors. This process not only preserves functionality but also enhances code reliability and performance over time.

2. Identifying Bugs

2.1 Understanding Error Messages

Error messages typically contain crucial information, such as:

  • Error Type: Example: TypeError, ReferenceError, etc.
  • Description: Details about what went wrong.
  • Location: The file and line where the error occurred.

Properly understanding these messages is essential to determine the next step in solving the issue.

2.2 Using the Browser Console

The browser console, accessed via F12, is a powerful debugging tool. It allows you to:

  • View Errors: Displays all errors and warnings that occur on the page.
  • Execute Commands: Lets you test code directly in the console to verify the behavior of functions or variables.
  • Monitor Network: The "Network" tab lets you check HTTP requests, their responses, and possible communication errors.

2.3 Debugging in the Browser

Modern browsers have robust debugging tools accessible through DevTools (F12), including:

  • Console: To view logs, errors, and execute JavaScript code in real-time.
  • Sources: To inspect and debug code files.
  • Network: To monitor and analyze network requests.
  • Application: To inspect local storage, cookies, and other application resources.

2.4 Debugging JavaScript

  • Using Breakpoints: Breakpoints are points in the code where execution is paused, allowing you to inspect the current state of the application.
    • To set a breakpoint, open DevTools (F12), navigate to the Sources tab, find the desired JavaScript file, and click on the line number where you want to pause execution.
  • Analyzing Variables and Functions: With the code paused at a breakpoint, you can:
    • Hover over variables to see their current values.
    • Use the Scope tab to view the context of available variables.
    • Step through the code line by line using the "Step Over" or "Step Into" buttons.
  • Conditional Debugging: To focus on specific situations, such as when a variable takes an unexpected value:
    • Right-click on the line where you want to add the breakpoint.
    • Select "Add conditional breakpoint" and enter the condition.

2.5 Debugging React Applications

React applications introduce additional layers of complexity, but there are specific tools for debugging:

  • React Developer Tools: A browser extension that allows you to:
    • Inspect the component tree.
    • Debugging state: Monitor state and prop changes in real-time.
  • Debugging Hooks: React Developer Tools makes it easy to inspect the state of hooks within functional components.

3. Development Best Practices

3.1 Code Clarity and Maintainability

Well-structured code makes it easier to identify problems and maintain in the future. Some recommended practices include:

  • Descriptive Variable and Function Names: Choose names that clearly indicate the purpose of the variable or function.
  • Useful Comments: Document complex code sections or important architectural decisions.
  • Consistency: Maintain a consistent coding style using tools like ESLint or Prettier.

3.2 Avoid "Hacks"

Temporary solutions can become future problems that are difficult to resolve. Always prioritize a complete and sustainable solution.

4. The Importance of Unit Testing

4.1 What Are Unit Tests?

Unit tests are automated tests that verify whether individual parts of your code (units) are working as expected. They help identify problems even before the code is integrated into the main application.

4.2 How Tests Help Identify Bugs

By covering your code with unit tests, you ensure that new changes do not introduce bugs. If a test fails, you immediately know where and what went wrong, making it easier to fix.

4.3 Unit Testing Tools

There are several popular libraries for unit testing in frontend development, such as:

  • Jest: Widely used with React.
  • Mocha/Chai: Popular for testing in general JavaScript projects.
  • Cypress: For end-to-end testing, which also helps cover functionalities.

5. Security in Development

5.1 The Importance of Security

Security should be a constant concern in frontend development. Vulnerabilities can be exploited, compromising user data and application integrity.

5.2 Security Practices

  • Input Validation: Never blindly trust user-provided data. Always perform validations both on the frontend and backend.
  • Data Sanitization: Clean and process input data to prevent attacks such as XSS (Cross-Site Scripting).
  • Use HTTPS: Ensure that all communication between the client and server is securely done using HTTPS.

5.3 Monitoring Vulnerabilities

Keep your dependencies updated and use tools like Snyk or npm audit to monitor and fix known vulnerabilities.

6. Using Google Chrome DevTools

6.1 Breakpoint Toolbar

Image description

6.1.1 What Are Breakpoints?

Breakpoints are points in the code where execution is paused, allowing you to inspect the current state of the application.

6.1.2 How to Use Breakpoints

To use breakpoints:

  • Access DevTools: Press F12 or Ctrl + Shift + I (Windows/Linux) or Cmd + Option + I (Mac).
  • Go to the Sources tab.
  • Find the JavaScript file you want to debug.
  • Click on the line number where you want to add a breakpoint.

6.1.3 Breakpoint Toolbar

Shortcuts for the Breakpoint Toolbar:

  • Resume Script Execution: F8
  • Step Over (Skip Functions): F10
  • Step Into (Enter Function): F11
  • Step Out (Exit Function): Shift + F11
  • Deactivate Breakpoints: No default shortcut, but you can click the "Toggle Breakpoints" icon in the toolbar.

6.2 Sources Tab

Image description

6.2.1 Navigating Files

In the Sources tab, explore all the files loaded by the page.

Main shortcuts:

  • Quick Open File: Ctrl + P (Windows/Linux) or Cmd + P (Mac)
  • Search in File: Ctrl + F (Windows/Linux) or Cmd + F (Mac)
  • Navigate Breakpoints: Ctrl + Shift + B (Windows/Linux) or Cmd + Shift + B (Mac)

6.2.2 Using Conditional Breakpoints

To add conditional breakpoints:

  • Add Conditional Breakpoint: Right-click on the desired line and select "Add Conditional Breakpoint".
  • Shortcut to open the context menu: Shift + F10 (Windows/Linux)

6.3 Network Tab

Image description

6.3.1 Monitoring HTTP Requests

In the Network tab, monitor all requests made by the page.

Main shortcuts:

  • Reload the page with Network open: Ctrl + R (Windows/Linux) or Cmd + R (Mac)
  • Clear requests from the Network tab: Ctrl + E (Windows/Linux) or Cmd + E (Mac)

6.3.2 Simulating Network Conditions

Simulate different network conditions:

  • Throttle (Network Simulation): No default shortcut, but you can enable/disable simulations from the "Online" menu in the Network tab.

6.4 Application Tab

Image description

6.4.1 Inspecting Storage

In the Application tab, inspect and manipulate local storage, cookies, etc.

Main shortcuts:

  • No default shortcut for Application: Navigate using the mouse or combine with general DevTools shortcuts.

6.4.2 Managing Service Workers

Monitor active service workers in the Application tab. There are no dedicated shortcuts, but general DevTools commands like F12 to open and Esc to toggle panels can be used.

6.5 Performance Tab

Image description

6.5.1 Recording Performance Sessions

In the Performance tab, record the page's performance.

Main shortcuts:

  • Start/Stop Recording: Ctrl + E (Windows/Linux) or Cmd + E (Mac)
  • Take a performance snapshot: Ctrl + Shift + E (Windows/Linux) or Cmd + Shift + E (Mac)

6.6 Security Tab

Image description

6.6.1 Checking Security

In the Security tab, inspect the security of the page.

Main shortcuts:

  • No default shortcut: Use F12 to open DevTools and navigate to the Security tab.

6.7 Lighthouse

Image description

6.7.1 Running Audits

In the Lighthouse tab, run automated audits.

Main shortcuts:

  • No default shortcut to start audits: Click on "Generate report" manually.

6.8 Chrome Inspector

6.8.1 Accessing the Chrome Inspector

Main shortcuts to access and use Chrome Inspector:

  • Open DevTools directly to the Elements tab: Ctrl + Shift + C (Windows/Linux) or Cmd + Shift + C (Mac)
  • Select element to inspect: Ctrl + Shift + C (Windows/Linux) or Cmd + Shift + C (Mac)
  • Switch between panels (Elements, Console, etc.): Ctrl + or Ctrl + or Cmd + or Cmd +

6.8.2 Inspecting HTML Elements

  • Select element on the page: Ctrl + Shift + C (Windows/Linux) or Cmd + Shift + C (Mac)
  • Edit HTML directly: Click on the element and start editing. There is no specific shortcut, but the process is highly intuitive.

6.8.3 Modifying CSS in Real-Time

Shortcuts to modify CSS:

  • Edit CSS rule value: Click on the rule in the Styles panel.
  • Navigate between CSS rules: Up/Down arrows to move between properties.
  • Enable/disable a CSS rule: Alt + Click on the checkbox next to the rule.

6.8.4 Computed Styles

  • Switch between Styles and Computed: Use the mouse, there is no default shortcut.

6.8.5 Box Model

  • Inspect and adjust margins, borders, etc.: There are no specific shortcuts, but click and drag allows for quick adjustments.

6.8.6 Debugging Pseudo-Classes

  • Force Element State (e.g., :hover, :active): Click on the forced styles icon in the Styles panel, there is no dedicated shortcut.

6.8.7 Accessibility

  • Inspect element accessibility in the Elements tab: Use the shortcut Ctrl + Shift + C followed by manual navigation to the accessibility sub-tab.

7. Conclusion

This guide has been crafted based on my readings and personal experience in frontend development, providing a comprehensive starting point for effective debugging, best coding practices, and security measures. However, our field is ever-evolving, with new tools, techniques, and challenges emerging every day. There is always more to learn and explore, as our industry continually improves and shifts. Embrace this journey, and keep pushing the boundaries of your knowledge and skills in this dynamic world of technology.

References

  1. Google Chrome DevTools Overview
  2. MDN Web Docs: Debugging JavaScript
  3. React Developer Tools
  4. Jest Documentation
  5. Mocha Documentation
  6. Cypress Documentation
  7. Google Lighthouse
  8. Snyk: Find & Fix Vulnerabilities
  9. npm Audit
  10. MDN Web Docs: Security
  11. MDN Web Docs: HTML Accessibility
  12. Prettier Documentation
  13. ESLint Documentation
  14. Google Chrome DevTools: JavaScript
  15. JavaScript Debugging in Chrome
  16. Google Chrome DevTools: Sources
  17. Google Chrome DevTools: DOM
  18. Google Chrome DevTools: Console
  19. Google Chrome DevTools: Network
  20. Google Chrome DevTools: Performance Overview
  21. Google Chrome DevTools: Memory
  22. Google Chrome DevTools: Progressive Web Apps
  23. Google Chrome DevTools: Recorder Overview
  24. Google Chrome DevTools: Rendering
  25. JavaScript Debugging in Chrome
  26. VSCode Documentation: Browser Debugging
  27. Chrome Inspector - UW Courses
  28. Learn to Debug JavaScript Using Chrome Debugger
  29. React Community: Debugging Tools
  30. DevMedia: Depurando JavaScript com Google Chrome
  31. Medium: Depurando código JavaScript com Google Chrome
  32. Martin, Robert C. Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall, 2008.
  33. Resig, John, e Bear Bibeault. Secrets of the JavaScript Ninja. Manning Publications, 2016.
  34. Mackenzie, Kyle. JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language. O'Reilly Media, 2020.
  35. Osmani, Addy. Learning JavaScript Design Patterns: A JavaScript and jQuery Developer's Guide. O'Reilly Media, 2012.

Top comments (0)