Debugging JavaScript

</>Coding Tamilan.← JavaScript course

JavaScript · Lesson 31 / 32 · English

Debugging JavaScript

Understand the idea. Change the code. Build confidence with one focused experiment.

Detailed notesRunnable JavaScriptPractice + answer

Read this lesson in தமிழ் ↗.

01 / Understand

Start with the idea

Debugging is a process: reproduce the failure, inspect values, identify the first incorrect assumption, then verify the fix. Log inputs as well as results.

Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.

02 / Explore

Step-by-step lesson notes

Debugging JavaScript

Debugging is the process of finding and fixing errors in your code. JavaScript has powerful built-in tools and browser DevTools to help.

The debugger Statement

JavaScript reference fragmentCODE
function calculateTotal(items) {
  let total = 0;
  for (const item of items) {
    debugger; // ← execution PAUSES here in DevTools
    total += item.price;
  }
  return total;
}

// Open DevTools (F12) BEFORE calling the function
calculateTotal([{ price: 10 }, { price: 20 }]);

Remember: Remove debugger statements before committing code. They have no effect if DevTools is closed.

Advanced console Techniques

JavaScript reference fragmentCODE
// Named groups
console.group("📦 Order Processing");
console.log("Validating items...");
console.log("Calculating total...");
console.groupEnd();

// Count how many times a line is reached
for (let i = 0; i < 5; i++) {
  console.count("loop"); // "loop: 1", "loop: 2" ...
}
console.countReset("loop");

// Trace the call stack
function a() { b(); }
function b() { console.trace("How did I get here?"); }
a(); // shows full call stack

// Styled output
console.log(
  "%cError!",
  "color: red; font-size: 20px; font-weight: bold"
);

// Log with labels (object shorthand trick)
const x = 10, y = 20;
console.log({ x, y }); // { x: 10, y: 20 } — shows variable names!

Common JavaScript Errors

ErrorCauseFix
ReferenceError: x is not definedUsing variable before declaringDeclare with let/const/var
TypeError: x is not a functionCalling a non-function valueCheck the variable type
TypeError: Cannot read properties of nullAccessing property of null/undefinedAdd null check before access
SyntaxError: Unexpected tokenInvalid JS syntaxCheck for missing brackets or commas
RangeError: Maximum call stack exceededInfinite recursionAdd a base case to recursion

Defensive Debugging Patterns

JavaScript reference fragmentCODE
// 1. Type checking before use
function process(data) {
  if (!Array.isArray(data)) {
    console.error("Expected array, got:", typeof data, data);
    return;
  }
  // safe to use data as array
}

// 2. Optional chaining for deeply nested access
const city = user?.address?.city ?? "Unknown";

// 3. Structured error logging
try {
  const result = riskyOperation();
} catch (err) {
  console.error("[riskyOperation] Failed:", {
    message: err.message,
    stack: err.stack,
    input: someInput
  });
}

// 4. Assert-style helpers during development
function assert(condition, message) {
  if (!condition) throw new Error(`Assertion failed: ${message}`);
}
assert(Array.isArray(items), "items must be an array");
03 / Read & predict

A complete example

Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.

index.js · complete exampleCODE
const input = "20";
console.log("input type:", typeof input);
const amount = Number(input);
console.log("numeric type:", typeof amount);
console.log("total:", amount + 5);
Predict first. Reveal the expected result.
input type: string
numeric type: number
total: 25
04 / Experiment

Make one change. See what happens.

Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.

Open editor ↗

Wait for the editor to load, then load this example and press Run.

Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.

05 / Your turn

Put the idea to work

Practice challenge

Remove Number and predict the total.

Reveal the answer and reasoning

Without conversion, input + 5 produces "205". The type logs reveal why.

One mistake to avoid: Do not treat the last line of a stack trace as the root cause automatically. Read the error message and find the relevant application frame.

Your learning checkpoint

  • Explain the example in your own words.
  • Complete the challenge before revealing its answer.
  • Describe the common mistake and how to avoid it.
Coding Tamilan · Learn by doing.