JavaScript and TypeScript course ยท Module 5: Advanced JavaScript

Breakpoints and Step-by-Step Code Execution

10 min read ยท
In this lesson8

In the previous exercise we learned about the browser console and its logging functions. However, even the best console messages can be insufficient when dealing with complex bugs in the Jurassic Park management system. What if the validateDinosaurContainment() function returns an incorrect result but we don't know why? What if the predator behavior tracking algorithm has a subtle bug?

In such cases we need the ability to pause code execution at a specific point and analyze the application state. This is where breakpoints and step-by-step code execution come in - some of the most powerful JavaScript debugging techniques.

What Are Breakpoints?

A breakpoint is a marker placed in code that tells the browser to stop code execution when it reaches that point. This allows detailed examination of the application state at a chosen moment - we can check variable values, inspect the call stack, and execute code step by step.

Setting Breakpoints in the Browser

There are several ways to set breakpoints in the browser:

1. Breakpoints in the Sources/Debugger Panel

The simplest way is to use the Sources panel (Chrome) or Debugger panel (Firefox):

  1. Open developer tools (<kbd>F12</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd>)
  2. Go to the "Sources" tab (Chrome) or "Debugger" tab (Firefox)
  3. Find and open the file where you want to set a breakpoint
  4. Click the line number where you want to pause execution
  5. A blue arrow or marker will appear at the selected point, indicating an active breakpoint

For example, we may want to pause execution when checking fence status in Jurassic Park:

function checkFenceStatus(sectorId) {
  const sector = getSector(sectorId); // Set breakpoint on this line

  if (!sector) {
    throw new Error(`Unknown sector: ${sectorId}`);
  }

  const fenceStatus = sector.fence.getStatus();

  if (fenceStatus !== 'active') {
    triggerAlarm(sectorId, `Fence failure: ${fenceStatus}`);
  }

  return fenceStatus;
}

After setting the breakpoint, when checkFenceStatus() is called, the browser will pause execution at that line and we'll be able to check the value of sectorId and other available variables.

2. Programmatic Breakpoints with the debugger Statement

Sometimes it's more convenient to place a breakpoint directly in the code using the debugger statement:

function trackDinosaur(dinosaurId, location) {
  const dinosaur = getDinosaurById(dinosaurId);

  debugger; // Code will pause here when the function is called

  if (!dinosaur) {
    console.error(`Dinosaur not found with ID: ${dinosaurId}`);
    return false;
  }

  updateDinosaurLocation(dinosaurId, location);
  checkContainmentStatus(dinosaurId, location);

  return true;
}

The debugger statement is ignored when developer tools are not open, but when active, the browser pauses execution at that point.

3. Conditional Breakpoints

Sometimes we want to pause execution only when a certain condition is met - for example, when tracking a dinosaur with a specific ID or when the danger level exceeds a value:

Setting via Browser Interface

  1. Set a regular breakpoint by clicking the line number
  2. Right-click on the breakpoint
  3. Select "Edit breakpoint" or "Add condition"
  4. Enter a condition, for example: dinosaurId === 'TRX-01' or dangerLevel > 8

Programmatic Conditional Pause

We can also use a conditional construct with the debugger statement:

function monitorDinosaurBehavior(dinosaur) {
  const behaviorPattern = analyzeBehavior(dinosaur);
  const dangerLevel = assessThreatLevel(behaviorPattern);

  // Pause execution only if the danger level is high
  if (dangerLevel > 8) {
    debugger; // Will pause only for high danger levels

    // Code to handle dangerous behaviors
    activateEmergencyProtocol(dinosaur.id, dangerLevel);
  }

  return {
    dinosaurId: dinosaur.id,
    behaviorPattern,
    dangerLevel,
    timestamp: new Date()
  };
}

Step-by-Step Code Execution

When code is paused at a breakpoint, we have several step execution options that allow controlled traversal of the code:

1. Step Over (F10)

Executes the current line and stops at the next line in the same function. If the current line contains a function call, that function is executed entirely (we don't step inside it).

function monitorParkSystems() {
  checkSecuritySystems();     // Step Over executes this entire function...
  checkDinosaurContainment(); // ...and stops here
  checkVisitorSafety();
}

2. Step Into (F11)

Executes the current line, but if the line contains a function call, the debugger "enters" that function and stops at its first line.

function monitorParkSystems() {
  checkSecuritySystems();     // Step Into will enter this function...
  checkDinosaurContainment(); // ...instead of moving here
  checkVisitorSafety();
}

function checkSecuritySystems() {
  const fenceStatus = checkFences();   // ...and will stop here
  const cameraStatus = checkCameras();
  const gateStatus = checkGates();

  return { fenceStatus, cameraStatus, gateStatus };
}

3. Step Out (Shift+F11)

Executes the remaining part of the current function and stops after returning from the function, at the point where it was called.

function checkSecuritySystems() {
  const fenceStatus = checkFences();
  const cameraStatus = checkCameras(); // If we are here...
  const gateStatus = checkGates();

  return { fenceStatus, cameraStatus, gateStatus };
}

function monitorParkSystems() {
  checkSecuritySystems();     // ...Step Out executes the rest of the function and stops here
  checkDinosaurContainment();
  checkVisitorSafety();
}

4. Continue (F8)

Resumes code execution until the next breakpoint is encountered or the script finishes.

Inspecting Variables and State

When code is paused at a breakpoint, we can thoroughly examine the application state:

1. Scope/Variables Panel

One of the most important panels during debugging - shows all available variables in the current scope:

  • Local - local variables in the current function
  • Closure - variables from closures (parent functions)
  • Global - global variables
  • this - the value of this in the current context

For example, when debugging a function monitoring dinosaur behavior:

function analyzeDinosaurBehavior(dinosaur, environmentalFactors) {
  const { species, previousBehaviors, lastFeeding } = dinosaur;
  const { weather, timeOfDay, nearbyDinosaurs } = environmentalFactors;

  const timeSinceFeeding = Date.now() - lastFeeding;
  const isHungry = timeSinceFeeding > getSpeciesFeedingThreshold(species);

  debugger; // pause here

  // At this point the Scope panel will show:
  // - Local: dinosaur, environmentalFactors, species, previousBehaviors, lastFeeding,
  //          weather, timeOfDay, nearbyDinosaurs, timeSinceFeeding, isHungry
  // - Global: global objects and functions

  const behaviorPrediction = predictBehavior(
    species, previousBehaviors, isHungry, weather, timeOfDay, nearbyDinosaurs
  );

  return {
    dinosaurId: dinosaur.id,
    prediction: behaviorPrediction,
    riskLevel: assessRiskLevel(behaviorPrediction),
    isHungry,
    timestamp: new Date()
  };
}

2. Watch Expressions

The Watch panel lets you add expressions to monitor during debugging. This is especially useful for complex expressions or values not directly visible in the Scope panel:

// We can add watched expressions such as:
dinosaur.species === 'Velociraptor'
getDistanceFromFence(dinosaur.location)
isInDangerZone(dinosaur.location, restrictedSectors)

3. Console in Debug Mode

While paused at a breakpoint, the console operates in the context of the current code position. We can execute expressions that have access to all variables visible in the current scope:

// In the console we can type:
dinosaur.species
timeSinceFeeding / (1000 * 60 * 60) // Convert milliseconds to hours
nearbyDinosaurs.filter(d => d.species === 'Velociraptor')

This is a powerful way to interactively explore the application state and run experiments without modifying code.

Practical Debugging Techniques for Jurassic Park

1. Debugging Asynchronous Code

Jurassic Park systems often use asynchronous operations - fetching data from sensors, communicating with security systems, etc. Debugging such code requires special techniques:

async function monitorsEnvironmentalSensors() {
  try {
    console.log("Starting sensor monitoring...");

    // Asynchronously fetch sensor data
    const temperatureData = await fetchSensorData('temperature');
    debugger; // Breakpoint pauses after receiving the response

    const humidityData = await fetchSensorData('humidity');
    const windData = await fetchSensorData('wind');

    const environmentalRisk = analyzeEnvironmentalRisk(
      temperatureData, humidityData, windData
    );

    if (environmentalRisk.level === 'high') {
      notifyParkManagement(`High environmental risk detected: ${environmentalRisk.reason}`);
    }

    return environmentalRisk;
  } catch (error) {
    console.error("Sensor monitoring error:", error);
    triggerBackupSystems();
    return { level: 'unknown', reason: 'error' };
  }
}

In modern browser developer tools, breakpoints work correctly with async functions - execution will pause at the debugger point, even after await operations.

2. Pausing on Exceptions

In a complex system like Jurassic Park, errors can appear in unexpected places. Instead of manually setting breakpoints, we can configure the debugger to pause when an exception occurs:

  1. Open the Sources/Debugger panel
  2. Find the "Breakpoints" section
  3. Check "Pause on exceptions"
  4. Optionally: check "Pause on caught exceptions"

Now the browser will pause execution when any unhandled exception occurs, greatly simplifying identification of the source of problems.

3. Source Maps

In production applications, JavaScript code is often minified and bundled, making debugging difficult. Source maps allow browsers to show and debug the original source code, even when minified code is being executed:

// webpack.config.js
module.exports = {
  devtool: 'source-map', // Generate source maps for all files
};

For Jurassic Park, where safety is a priority, this is a critical feature that enables fast debugging of production issues.

Debugging in Practice - Case Study

Let's analyze a practical example of debugging a problem in the dinosaur monitoring system:

class DinosaurMonitoringSystem {
  constructor() {
    this.activeMonitors = new Map();
    this.alertLevel = 'normal';
  }

  checkDinosaurStatus(dinosaurId) {
    const monitor = this.activeMonitors.get(dinosaurId);

    if (!monitor) {
      console.error(`No active monitoring for dinosaur ${dinosaurId}`);
      return null;
    }

    try {
      const dinosaur = getDinosaurById(dinosaurId);
      const location = getLastKnownLocation(dinosaurId);
      const vitalSigns = getVitalSigns(dinosaurId);

      // BUG: Not checking if location exists!
      const inContainment = isInContainmentZone(location.coordinates);

      const reading = {
        timestamp: Date.now(),
        location,
        vitalSigns,
        inContainment
      };

      monitor.readings.push(reading);
      monitor.locationStatus = inContainment ? 'contained' : 'breach';

      return reading;
    } catch (error) {
      console.error(`Error checking status for dinosaur ${dinosaurId}:`, error);
      return null;
    }
  }
}

Step 1: Identify the Problem

During testing, the monitoring system unexpectedly reports 'critical' alert level for some dinosaurs, even though they are safely in their enclosures.

Step 2: Set Breakpoints

We set a breakpoint in checkDinosaurStatus to investigate:

checkDinosaurStatus(dinosaurId) {
  const monitor = this.activeMonitors.get(dinosaurId);
  if (!monitor) { return null; }

  debugger; // Set breakpoint here to examine all variables

  try { /* ...rest of code */ }
}

Step 3: Step Through and Analyze

  1. Step through code using "Step Into" and "Step Over"
  2. We reach the line checking location status:
    const inContainment = isInContainmentZone(location.coordinates);
  3. Check the location variable in the Scope panel - it's null
  4. Identified problem: getLastKnownLocation sometimes returns null when it can't find the location, and the code doesn't check for this before accessing location.coordinates

Step 4: Fix the Bug

// Safer code with verification
const location = getLastKnownLocation(dinosaurId);
const inContainment = location && location.coordinates
  ? isInContainmentZone(location.coordinates)
  : false; // If we don't know the location, assume the worst

Step 5: Verify the Solution

After fixing the bug, remove the breakpoint and test the system again. This time it works correctly without reporting false alarms.

Best Practices for Debugging

  1. Use meaningful variable names - makes identifying variables during debugging easier
  2. Add documentation to functions - JSDoc comments help understand the purpose and expected values
  3. Logically structure code - clean code is easier to debug
  4. Use defensive programming - validate inputs and handle edge cases
  5. Create small, dedicated functions - functions with single responsibility are easier to debug
  6. Use try-catch for potentially problematic code - helps localize error sources
  7. Avoid modifying debugged variables - it can change program behavior

Summary

Breakpoints and step-by-step code execution are invaluable tools in the arsenal of every developer working on Jurassic Park systems. They allow:

  • Pausing code execution at critical moments
  • Examining application state, variable values, and execution context
  • Executing code step by step to understand its flow
  • Identifying error sources, especially in complex systems
  • Verifying correctness of functions and modules

Remember that in Jurassic Park, the ability to quickly find and fix bugs can be a matter of life or death - both for the code and (in a real park) for the visitors!

Code for this lesson: main.js
// Circular Dependencies - Jurassic Park
// Handling circular dependencies in modules

console.log("Circular Dependencies");
console.log("How to handle mutual module dependencies\n");

// ===========================================
// PROBLEM: Circular Dependencies
// ===========================================

// === dinosaur-manager.js ===
class DinosaurManager {
  constructor() {
    this.dinosaurs = new Map();
  }

  addDinosaur(dinosaur) {
    this.dinosaurs.set(dinosaur.id, dinosaur);
    // Problem: we need SecuritySystem, but it also needs DinosaurManager
    console.log(`Added dinosaur: ${dinosaur.name}`);
  }

  getDinosaur(id) {
    return this.dinosaurs.get(id);
  }

  getAllDinosaurs() {
    return Array.from(this.dinosaurs.values());
  }
}

// === security-system.js ===
class SecuritySystem {
  constructor(dinosaurManager) {
    this.dinosaurManager = dinosaurManager;
    this.securityLevel = 'GREEN';
  }

  checkSecurity() {
    const dinosaurs = this.dinosaurManager.getAllDinosaurs();
    const dangerousDinos = dinosaurs.filter(d => d.dangerLevel > 7);

    if (dangerousDinos.length > 2) {
      this.securityLevel = 'RED';
    } else if (dangerousDinos.length > 0) {
      this.securityLevel = 'YELLOW';
    } else {
      this.securityLevel = 'GREEN';
    }

    console.log(`Security level: ${this.securityLevel}`);
    return this.securityLevel;
  }

  alertForDinosaur(dinosaur) {
    if (dinosaur.dangerLevel > 7) {
      console.log(`ALERT: ${dinosaur.name} is dangerous!`);
    }
  }
}

// === dinosaur.js ===
class Dinosaur {
  constructor(name, species, dangerLevel, securitySystem) {
    this.id = Math.random().toString(36).substr(2, 9);
    this.name = name;
    this.species = species;
    this.dangerLevel = dangerLevel;
    this.securitySystem = securitySystem;
  }

  roar() {
    console.log(`${this.name}: ROAAR!`);
    // Problem: we need SecuritySystem, which needs DinosaurManager
    if (this.securitySystem) {
      this.securitySystem.alertForDinosaur(this);
    }
  }
}

// ===========================================
// SOLUTION 1: Dependency Injection
// ===========================================

console.log("=== SOLUTION 1: Dependency Injection ===\n");

const manager = new DinosaurManager();
const security = new SecuritySystem(manager);

const trex = new Dinosaur('Rexy', 'T-Rex', 9, security);
const raptor = new Dinosaur('Blue', 'Velociraptor', 7, security);
const brachi = new Dinosaur('Gentle Giant', 'Brachiosaurus', 2, security);

manager.addDinosaur(trex);
manager.addDinosaur(raptor);
manager.addDinosaur(brachi);

console.log("\nChecking security...");
security.checkSecurity();

console.log("\nSound test:");
trex.roar();
raptor.roar();
brachi.roar();

// ===========================================
// SOLUTION 2: Event System
// ===========================================

console.log("\n=== SOLUTION 2: Event System ===\n");

class EventBus {
  constructor() {
    this.listeners = {};
  }

  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  }

  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => callback(data));
    }
  }
}

const eventBus = new EventBus();

class DinosaurManagerV2 {
  constructor(eventBus) {
    this.eventBus = eventBus;
    this.dinosaurs = new Map();

    // Listen for events
    this.eventBus.on('dinosaur:added', (dino) => {
      console.log(`Event: Added ${dino.name}`);
    });
  }

  addDinosaur(dinosaur) {
    this.dinosaurs.set(dinosaur.id, dinosaur);
    this.eventBus.emit('dinosaur:added', dinosaur);
  }

  getAllDinosaurs() {
    return Array.from(this.dinosaurs.values());
  }
}

class SecuritySystemV2 {
  constructor(eventBus) {
    this.eventBus = eventBus;
    this.securityLevel = 'GREEN';

    // Listen for events
    this.eventBus.on('dinosaur:added', (dino) => {
      this.evaluateThreat(dino);
    });
  }

  evaluateThreat(dinosaur) {
    if (dinosaur.dangerLevel > 7) {
      console.log(`Event Security: ${dinosaur.name} requires monitoring`);
      this.securityLevel = 'YELLOW';
    }
  }
}

const eventBusInstance = new EventBus();
const managerV2 = new DinosaurManagerV2(eventBusInstance);
const securityV2 = new SecuritySystemV2(eventBusInstance);

console.log("Adding dinosaurs with the event system:");
managerV2.addDinosaur({ id: '1', name: 'Rex Jr', dangerLevel: 8 });
managerV2.addDinosaur({ id: '2', name: 'Herbivore', dangerLevel: 2 });

// ===========================================
// SOLUTION 3: Lazy Loading / Late Binding
// ===========================================

console.log("\n=== SOLUTION 3: Lazy Loading ===\n");

class DinosaurManagerV3 {
  constructor() {
    this.dinosaurs = new Map();
    this._securitySystem = null;
  }

  setSecuritySystem(security) {
    this._securitySystem = security;
  }

  addDinosaur(dinosaur) {
    this.dinosaurs.set(dinosaur.id, dinosaur);
    console.log(`Lazy: Added ${dinosaur.name}`);

    // Lazy evaluation - security is available only now
    if (this._securitySystem) {
      this._securitySystem.checkSecurity();
    }
  }

  getAllDinosaurs() {
    return Array.from(this.dinosaurs.values());
  }
}

class SecuritySystemV3 {
  constructor() {
    this._dinosaurManager = null;
  }

  setDinosaurManager(manager) {
    this._dinosaurManager = manager;
  }

  checkSecurity() {
    if (!this._dinosaurManager) {
      console.log("DinosaurManager has not been assigned yet");
      return;
    }

    const dinosaurs = this._dinosaurManager.getAllDinosaurs();
    console.log(`Checking security for ${dinosaurs.length} dinosaurs`);
  }
}

const managerV3 = new DinosaurManagerV3();
const securityV3 = new SecuritySystemV3();

// Set references after creating both objects
managerV3.setSecuritySystem(securityV3);
securityV3.setDinosaurManager(managerV3);

managerV3.addDinosaur({ id: '1', name: 'Test Dino', dangerLevel: 5 });

console.log("\n=== BEST PRACTICES ===\n");
console.log("Dependency Injection:");
console.log("   - Pass dependencies through constructor/parameters");
console.log("   - Testable and predictable\n");

console.log("Event System:");
console.log("   - Loose coupling between modules");
console.log("   - Scalable for many subscribers\n");

console.log("Lazy Loading:");
console.log("   - Delayed dependency binding");
console.log("   - Good for optional dependencies\n");

console.log("AVOID:");
console.log("   - Direct require/import creating cycles");
console.log("   - Global variables as solutions");
console.log("   - Tight coupling between modules\n");

console.log("Demo completed!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Hands-on tasks in the game

  • Vertical ordering

    Order the code debugging stages from start to finish:

  1. Put in orderCode Debugging Stages

Useful articles