Intermediate

Debugging & Fixing

Use Copilot Chat to explain complex code, identify and fix bugs, understand error messages, optimize performance, and detect security vulnerabilities.

Explaining Code with /explain

The /explain command breaks down code into plain English. Select code in your editor and use this command to understand unfamiliar code, legacy systems, or complex algorithms.

Code to Explain
const memoize = (fn) => {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
};
Chat Prompt & Response
/explain Explain this function step by step

Copilot's response:
This is a memoization higher-order function:

1. It takes a function fn as input
2. Creates a Map called cache to store results
3. Returns a new function that:
   a. Converts arguments to a JSON string as a cache key
   b. Checks if the result is already cached
   c. If cached, returns the stored result (skipping computation)
   d. If not cached, calls the original function, stores the
      result, and returns it

This pattern improves performance by avoiding redundant
calculations for the same inputs.
Depth control: You can ask for different levels of detail. Try "Explain this at a high level" for a summary, or "Explain this line by line" for detailed analysis. You can also ask "Explain this as if I'm a junior developer" for simpler explanations.

Fixing Bugs with /fix

The /fix command analyzes selected code for bugs and proposes corrections. It identifies common issues like off-by-one errors, null reference problems, incorrect logic, and more.

Buggy Code
function findUser(users, id) {
  for (let i = 0; i <= users.length; i++) {  // Bug: off-by-one
    if (users[i].id == id) {                  // Bug: loose equality
      return users[i];
    }
  }
  return null;
}
Chat Prompt
/fix Find and fix all bugs in this function
Fixed Code
function findUser(users, id) {
  for (let i = 0; i < users.length; i++) {   // Fixed: use < not <=
    if (users[i].id === id) {                 // Fixed: strict equality
      return users[i];
    }
  }
  return null;
}

Understanding Error Messages

When you encounter an error message you do not understand, paste it into Copilot Chat for an explanation. Copilot will break down the error and suggest solutions.

Chat Prompt
// Paste the error message directly
I'm getting this error:

TypeError: Cannot read properties of undefined
(reading 'map')
  at UserList (UserList.tsx:15:23)
  at renderWithHooks (react-dom.development.js:14985)

What does this mean and how do I fix it?

Copilot Chat will explain that the code is trying to call .map() on a variable that is undefined, likely because data has not loaded yet. It will suggest solutions like optional chaining, default values, or conditional rendering.

Using @terminal for Terminal Errors

The @terminal participant has access to your terminal context. When you encounter errors while running commands, use @terminal to get help.

@terminal Examples
@terminal I just ran npm install and got an ERESOLVE
error. How do I fix the dependency conflict?

@terminal Why is my Docker container exiting with
code 137?

@terminal The build command failed. What went wrong?
💡
Terminal context: @terminal can see your recent terminal output, so it often does not need you to paste the full error. It can reference the error that just appeared in your terminal automatically.

Step-by-Step Debugging Assistance

For complex bugs, engage Copilot Chat in a multi-turn debugging conversation. Walk through the problem systematically:

  1. Describe the Symptom

    Tell Copilot what is happening vs what should happen: "This function returns undefined instead of the filtered array when the input has duplicate values."

  2. Share the Code

    Select the relevant code or use #file to reference it: "Here is the function in #file:src/utils/filter.ts"

  3. Provide Test Cases

    Share inputs and expected vs actual outputs: "When I pass [1, 2, 2, 3], I expect [1, 3] but I get undefined."

  4. Iterate

    Ask follow-up questions: "That fix works but now it fails for empty arrays. How do I handle that edge case?"

Performance Optimization

Copilot Chat can identify performance bottlenecks and suggest optimizations. Select slow code and ask for improvements.

Performance Prompts
// General optimization
How can I optimize this function for better performance?

// Specific concerns
This query is slow on large datasets. How can I improve
the time complexity?

// Memory optimization
This function uses too much memory. How can I reduce
its memory footprint?

// Database queries
This page loads slowly. Analyze #file:src/api/posts.ts
for N+1 query problems
Before: O(n^2) Solution
function findDuplicates(arr) {
  const duplicates = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
        duplicates.push(arr[i]);
      }
    }
  }
  return duplicates;
}
After: O(n) Solution (Copilot Suggestion)
function findDuplicates(arr) {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) {
      duplicates.add(item);
    } else {
      seen.add(item);
    }
  }
  return [...duplicates];
}

Security Vulnerability Detection

Copilot Chat can review code for common security vulnerabilities like SQL injection, XSS, insecure authentication, and exposed secrets.

Security Review Prompts
// General security review
Review this code for security vulnerabilities

// Specific concerns
Is this query vulnerable to SQL injection?

// Authentication review
Review the authentication flow in
#file:src/auth/login.ts for security issues

// Input validation
Does this API endpoint properly validate and
sanitize user input?
Not a replacement for security audits: While Copilot Chat can identify many common vulnerabilities, it should not be your only security measure. Always conduct thorough security reviews, use static analysis tools, and follow your organization's security practices.

💡 Try It: Debug a Bug

Find a function in your project that has a known issue or that you suspect could be improved. Try this debugging workflow:

This systematic approach — understand, fix, test — is the most effective way to use Copilot Chat for debugging. The AI catches issues that are easy to overlook during manual review.