💻 Programming

Debugging

Debugging

The process of finding and fixing software errors. Uses IDE debuggers, logging, and profiling.

📖 Detailed Explanation

Debugging is the entire process of finding a bug in software, analyzing its cause, and fixing it. The term "debugging" originated in 1947 when Grace Hopper of Harvard University discovered an actual moth (bug) in the Mark II computer, and today it refers to the act of fixing all kinds of software errors.

The core debugging techniques include breakpoints, logging, and step execution. A breakpoint pauses execution at a specific point in the code so that variable values and program state can be inspected, and logging records important information during execution so that it can be used for tracing when a problem occurs.

Modern IDEs come with powerful built-in debugging tools. Tools such as VS Code, IntelliJ IDEA, and Chrome DevTools provide advanced features such as conditional breakpoints, variable watching (Watch), call stack tracing, and memory profiling, making it possible to trace even complex bugs efficiently.

Effective debugging requires a systematic approach. First reproduce the bug, form a hypothesis, and then narrow down the scope using a binary search approach to find the cause. In the AI era, tools such as GitHub Copilot and ChatGPT are being used for error message analysis and for suggesting solutions.

💻 Code Example

// 1. 로깅을 활용한 디버깅
function calculateTotal(items) {
    console.log('[DEBUG] 입력 아이템:', items);

    let total = 0;
    for (const item of items) {
        console.log(`[DEBUG] 처리 중: ${item.name}, 가격: ${item.price}`);
        total += item.price * item.quantity;
    }

    console.log('[DEBUG] 최종 합계:', total);
    return total;
}

// 2. 조건부 로깅 (프로덕션에서 활용)
const DEBUG = process.env.NODE_ENV !== 'production';

function debugLog(...args) {
    if (DEBUG) {
        console.log(new Date().toISOString(), ...args);
    }
}

// 3. try-catch를 활용한 에러 추적
async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        if (!response.ok) {
            throw new Error(`HTTP 에러: ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        // 에러 컨텍스트와 함께 로깅
        console.error('사용자 데이터 조회 실패:', {
            userId,
            error: error.message,
            stack: error.stack
        });
        throw error;
    }
}

// 4. 브레이크포인트 대체: debugger 문
function complexCalculation(data) {
    const result = data.map(item => {
        debugger; // 브라우저 DevTools에서 여기서 멈춤
        return item.value * 2;
    });
    return result;
}

// 5. 성능 디버깅: console.time 활용
console.time('데이터 처리');
processLargeDataset(data);
console.timeEnd('데이터 처리'); // 출력: 데이터 처리: 1234.56ms

🗣️ Say It Like This in Practice

💬 In a Meeting
"This bug has tricky reproduction conditions, so I'll first strengthen the logging and then debug in the staging environment. In production, it would be good to attach Sentry as an error tracking tool and monitor in real time."
💬 In an Interview
"When debugging, I first make the bug reproducible, then narrow down the scope of the problem using binary search. I mainly use the Network tab and Sources tab in Chrome DevTools, and for complex state issues I do time-travel debugging with Redux DevTools."
💬 In a code review
"You must not leave console.log in production code. For debugging logs, please use the debug library or control them with environment variables. Also, be sure to include the stack trace and context information in error logging."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Do not leave console.log in production

Debugging console.log statements cause performance degradation and security issues. Enable ESLint's no-console rule, or configure it so that they are automatically removed at build time.

❌
Verify, don't assume

If you assume "this part won't have any problems," you will miss bugs. Add logs or set breakpoints at every suspicious point and check the actual values.

❌
Find the root cause, not just fix the symptoms

If you only handle the error in front of you, the same bug will recur elsewhere. Analyze why this bug occurred and resolve it structurally.

✅
Build a systematic error tracking system

Adopt error tracking tools such as Sentry, Datadog, and LogRocket. You can detect production errors in real time and check stack traces and user context together.

🔗 Related Terms

📚 Learn More