Student Programming Guide

Cracking the 9.7.4 Leash Codehs Answers Exercise — Logic First, Code Second

Most students who struggle with this exercise aren't struggling with code — they're struggling with how to think about it. This guide breaks the leash concept into clear mental models, walks through both the JavaScript and OOP versions with annotated examples, and explains every mistake worth avoiding.

Unit 9 · Animation & Games JavaScript + OOP Versions ~12 min read Beginner–Intermediate

01 What the 9.7.4 Leash Exercise Actually Tests

The 9.7.4 leash CodeHS exercise sits inside Unit 9 of the CodeHS curriculum — the unit dedicated to animation, graphics, and interactive games. It is one of the most concept-dense exercises in the entire course.

CodeHS is used by over 15,000 schools in the United States as of 2023, according to their public platform data. Unit 9 appears across their JavaScript Fundamentals, AP Computer Science Principles, and Introduction to Programming tracks.

Lesson 9.7.4 is not testing whether you can memorize syntax. It tests four things specifically:

📐

Spatial Reasoning

Can you think about objects as coordinates on a grid and predict how they move?

🖱️

Event Handling

Can you write code that reacts to user input in real time, not just once at startup?

📏

Conditional Logic

Can you use a condition to decide when to move an object and when to leave it alone?

🔗

Object Relationships

Can you design classes or objects that hold references to other objects and communicate through them?

The "leash" is the constraint — the rule that governs how far apart two things can be. Once you internalize that one idea, the rest of the code becomes obvious.

02 Build the Right Mental Model Before You Code

The single biggest reason students copy code instead of writing it: they try to write before they understand. Here is the mental model you need.

Every leash exercise has three characters: a Leader, a Follower, and a Rule. Find those three things in your assignment and you've already solved half the problem.

The Three-Character Model

CharacterWhat It IsIn JS VersionIn OOP Version
LeaderThe thing being followedYour mouse cursorThe Dog object
FollowerThe thing that followsA ball or circle on canvasThe Leash object
RuleThe constraint / connectionA distance threshold + a visible lineAn instance variable storing the Dog reference

Why This Mental Model Matters

When you approach any future exercise — a game enemy that chases the player, a camera that follows a character, a UI element that snaps to another — this same three-character pattern will apply every time. CodeHS 9.7.4 is the first place you meet it formally.

According to a 2022 study in the Journal of Educational Psychology, students who form conceptual models before writing code produce 34% fewer errors and complete tasks 28% faster than students who start with syntax first. Concept before code — always.

03 Core CodeHS Tools You'll Use in This Exercise

Before writing a single line for the leash exercise, you need to be comfortable with these built-in CodeHS methods. Each one has a precise purpose — using the wrong one is the most common source of bugs.

Method / ConceptWhat It DoesReturn TypeCommon Mistake
setMouseMoveMethod(fn) Registers a function to fire on every mouse movement void Calling the function instead of passing its reference
e.getX() / e.getY() Returns the mouse cursor's X or Y coordinate at the moment of the event Number Using it outside the event handler where e is undefined
object.getCenter() Returns a Point object at the center of a shape Point {x, y} Treating the result as a number instead of accessing .x and .y
object.setPosition(x, y) Moves the object's top-left corner to (x, y) void Passing the center coordinates without subtracting the radius offset
removeAll() Clears every object from the canvas void Forgetting to re-add objects after clearing
drawLine(x1, y1, x2, y2) Draws a line segment between two coordinate pairs Line object Passing Point objects instead of raw x/y numbers
Math.sqrt() Returns the square root of a number — used in distance calculation Number Forgetting to square the differences before summing
Run a tiny test for each method before you build the full exercise. Create a circle, call getCenter(), log the result, and inspect the output. Understanding your tools before you need them under pressure is a professional habit.

04 Two Versions of the Exercise — Which One Do You Have?

This assignment appears across multiple CodeHS courses and often looks very different. Identify your version first — the logic is related but the implementation is completely different.

Version A — JavaScript Canvas
  • Works with a visual canvas — you see a ball moving
  • A line (the leash) is drawn between the ball and the mouse or anchor point
  • Uses mouse event handlers, removeAll(), drawLine()
  • Focuses on real-time interaction and animation
  • Found in: JS Fundamentals, Intro to CS with JS
Version B — OOP / Class-Based
  • No canvas — purely object relationships
  • You create a Dog class and a Leash class
  • The Leash stores a reference to a Dog object
  • Focuses on constructors, instance variables, and encapsulation
  • Found in: AP CS A (Java), OOP-focused courses
Quick check: Does your assignment show a canvas with shapes moving? That's Version A. Does it ask you to create two classes and print information through one of them? That's Version B. Read your assignment description carefully — both appear under the same lesson number in different courses.

05 Version A Walkthrough — JavaScript Canvas Leash

This version creates a ball that follows your mouse on the canvas, connected by a visible leash line. Here is the full build, one logical step at a time.

1

Initialize Your Canvas Objects

Create the ball and set its starting position. The ball's starting point can be anywhere — the center of the canvas at (200, 200) is a clean default for a 400×400 canvas.

setup.js — Object Initialization
// Create the ball that will follow the mouse
var ball = new Circle(20);
ball.setColor(Color.blue);
ball.setPosition(200, 200);
add(ball);

// Define a fixed anchor point for the leash
var anchorX = 200;
var anchorY = 200;
2

Register the Mouse Move Handler

Pass your handler function as a reference — no parentheses. Adding parentheses here calls the function immediately instead of registering it.

events.js — Handler Registration
// ✓ Correct — passes reference
setMouseMoveMethod(mouseMove);

// ✗ Wrong — calls the function immediately
// setMouseMoveMethod(mouseMove());
3

Write the Handler — Clear, Move, Draw

Every mouse move fires this function. The pattern is always: clear the canvas, move the ball, draw the leash, re-add objects.

handler.js — mouseMove Function
function mouseMove(e) {
    // Step 1: get the mouse coordinates
    var mouseX = e.getX();
    var mouseY = e.getY();

    // Step 2: clear old drawings from canvas
    removeAll();

    // Step 3: position ball centered on cursor
    ball.setPosition(
        mouseX - ball.getRadius(),
        mouseY - ball.getRadius()
    );

    // Step 4: re-add the ball
    add(ball);

    // Step 5: get ball's center for line drawing
    var center = ball.getCenter();

    // Step 6: draw the leash line
    var leash = new Line(
        anchorX, anchorY,
        center.x, center.y
    );
    leash.setColor(Color.gray);
    add(leash);
}
4

Add the Distance Constraint (Leash Logic)

If your assignment requires the ball to only move when it's within a certain range, add a distance check before moving.

constraint.js — Distance Limit
function mouseMove(e) {
    var mouseX = e.getX();
    var mouseY = e.getY();

    // Calculate distance from anchor to mouse
    var dx = mouseX - anchorX;
    var dy = mouseY - anchorY;
    var dist = Math.sqrt(dx*dx + dy*dy);

    // Only move ball if within leash length (150px)
    if (dist <= 150) {
        removeAll();
        ball.setPosition(mouseX - 20, mouseY - 20);
        add(ball);
        var c = ball.getCenter();
        add(new Line(anchorX, anchorY, c.x, c.y));
    }
}
5

Verify Your Output Against This Checklist

  • The ball moves when you move the mouse
  • A line connects the anchor to the ball at all times
  • No trails or residual shapes appear on the canvas
  • The ball stays centered on the cursor (not offset to corner)
  • If using a distance limit: ball stops following when mouse goes too far

06 Version B Walkthrough — OOP Class-Based Leash

This version has no canvas. It teaches you how objects can hold other objects — a fundamental pattern in object-oriented programming. Java, Python, C#, and Swift all use this pattern daily in professional software.

1

Build the Dog Class

The Dog is the leader. It holds its own data — name, breed — and can report that data through a method.

Dog.js — Class Definition
class Dog {
    // Constructor stores the dog's data
    constructor(name, breed) {
        // "this" binds data to the object instance
        this.name = name;
        this.breed = breed;
    }

    // Returns a readable description of this dog
    describe() {
        return this.name + " is a " + this.breed;
    }
}
2

Build the Leash Class

The Leash holds a reference to a Dog. When you pass an object as a parameter, you're passing a reference — not a copy of the data. Both variables point to the same dog in memory.

Leash.js — Class Definition
class Leash {
    constructor(dog) {
        // Store the dog object as an instance variable
        this.dog = dog;
    }

    // Delegate to the dog's own describe() method
    getDogInfo() {
        return this.dog.describe();
    }
}
3

Wire Them Together in Main

Create the dog first. Then create the leash, passing the dog in. Access the dog's data only through the leash — that's the whole point of the exercise.

main.js — Putting It Together
// 1. Create a Dog object
var myDog = new Dog("Biscuit", "Golden Retriever");

// 2. Attach the dog to a leash
var myLeash = new Leash(myDog);

// 3. Access dog info through the leash
println(myLeash.getDogInfo());
// Output: Biscuit is a Golden Retriever
4

Understand Why This Pattern Matters

You've just built composition — one of the two core ways to build class relationships in OOP (the other is inheritance). According to the Gang of Four design patterns book (1994), "Favor object composition over class inheritance." You'll hear that advice for the rest of your programming career. You just practiced it.

07 8 Mistakes That Derail Students — And Exactly How to Fix Them

These eight errors account for the vast majority of failed submissions in Unit 9. Each one has a clear, fixable cause.

1
Mistake
Skipping removeAll() — leaves a trail of old objects on screen
Fix
Call removeAll() as the very first line inside your mouse handler, before touching anything else
2
Mistake
Treating getCenter() result as a number — throws "cannot read property x" error
Fix
Store the result: var c = obj.getCenter(); then use c.x and c.y separately
3
Mistake
Calling setMouseMoveMethod(mouseMove()) — the parentheses execute the function immediately
Fix
Remove the parentheses: setMouseMoveMethod(mouseMove) — pass the reference, not the result
4
Mistake
Ball positioned at top-left corner of cursor instead of center of cursor
Fix
Subtract the radius: setPosition(mouseX - radius, mouseY - radius)
5
Mistake
Forgetting to re-add the ball after calling removeAll()
Fix
After every removeAll(), explicitly call add(ball) again before drawing the line
6
Mistake
In OOP version: forgetting this. — data is lost when constructor finishes
Fix
Always write this.name = name, never just name = name — the left side must use this.
7
Mistake
Accessing dog data directly from myDog instead of through myLeash
Fix
The point of the exercise is the chain: call methods on the leash and let it delegate to the dog
8
Mistake
Distance check uses wrong reference points — checking from (0,0) instead of anchor
Fix
Calculate dx = mouseX - anchorX and dy = mouseY - anchorY using your actual anchor point

08 The Distance Formula — Made Completely Painless

You need to calculate straight-line distance between two points on the canvas. The formula comes from the Pythagorean theorem, which every student learns in geometry class, usually in Grade 7 or 8.

If you have point A at (x1, y1) and point B at (x2, y2), the distance between them is:

distance = √( (x2 − x1)² + (y2 − y1)² )
Euclidean Distance Formula — from Euclid's Elements, ~300 BCE

In JavaScript, you write it like this:

distance.js — JavaScript Implementation
function getDistance(x1, y1, x2, y2) {
    var dx = x2 - x1;  // horizontal gap
    var dy = y2 - y1;  // vertical gap
    return Math.sqrt(dx * dx + dy * dy);
}

// Usage example:
var dist = getDistance(anchorX, anchorY, mouseX, mouseY);

if (dist > 120) {
    // Mouse is outside leash range — don't move ball
} else {
    // Mouse is within range — update ball position
}
You can also use Math.pow(dx, 2) instead of dx * dx — both work. Most developers prefer the multiplication form because it's faster and easier to read.

09 Debugging Tactics That Actually Work

Use Console Output as Your First Diagnostic

Before you change any code, print values to understand what's happening. The console.log() function (or println() in CodeHS) is your best friend.

debug.js — Diagnostic Logging
function mouseMove(e) {
    // Print coordinates on every mouse move
    println("Mouse: " + e.getX() + ", " + e.getY());

    // Print ball center after moving
    var c = ball.getCenter();
    println("Ball center: " + c.x + ", " + c.y);
}

Three-Question Debugging Method

When something looks wrong, ask three questions in order:

QuestionHow to Check ItWhat the Answer Tells You
Is the handler even running? Add println("handler fired") as the first line If you see no output, the handler isn't registered properly
Are the coordinates correct? Print e.getX() and e.getY() every call If values don't change on mouse move, something is wrong with the event
Is the position being set? Print ball.getCenter() after setPosition() If position stays static, setPosition() may have wrong arguments
Remove all debug println() calls before submitting. Too many console outputs in CodeHS can slow down the animation loop significantly — sometimes making it look like your code is broken when it isn't.

10 Where the Leash Logic Appears in Real Software

The concepts in this exercise power real production software used by millions of people. Understanding this context makes the exercise feel less like busywork and more like training for an actual skill.

🎮
RPG Companions
Games like Zelda and Pokémon use follower logic with maximum distance before the follower teleports to catch up.
📷
Camera Follow
Unity's Cinemachine camera system uses smoothed distance-following — the same leader-follower pattern you just built.
🤖
Robotic Arms
Inverse kinematics in robotics uses chained joint constraints — each segment follows the next within a defined range.
🖥️
Node Editors
Figma, Blender, and Unreal Engine Blueprint all draw lines between connected nodes as you drag them — canvas line logic.
🎬
Bone Rigging
Character animation rigs in Maya or Spine use parent-child bone relationships with distance and angle constraints.

11 Study Smarter: How to Get More From Every CodeHS Exercise

01

Name Your Variables After What They Mean

Write distanceToMouse, not d. Write ballCenterX, not bcx. You read code more than you write it — make it readable to your future self.

02

Solve One Sub-Problem at a Time

Get the ball to appear before you add mouse tracking. Get mouse tracking to work before you add the line. Test each piece separately — then combine.

03

Draw the Data Flow on Paper

For the OOP version: draw arrows from mainLeashDog. Label each arrow with the method call. This makes class relationships physical and easy to reason about.

04

Re-Type — Don't Copy-Paste — Working Examples

When you see code that works, type it yourself from scratch rather than copy-pasting. Research from cognitive science shows that typing activates procedural memory, making patterns stick far longer.

05

After Finishing, Delete and Rebuild From Memory

Once you have a working solution, close it. Open a blank file. Rebuild it from scratch with only the assignment as your guide. This is the highest-return practice technique in programming education.

12 Semantic Keyword & Topical Authority Reference

The following topic clusters ensure this content covers the full semantic space around the core keyword for search engine topical authority.

ClusterSemantic Keywords & Phrases
Core Exercise9.7.4 leash codehs answers, codehs leash exercise, codehs unit 9 lesson 7, codehs animation unit leash
Platformcodehs javascript curriculum, codehs AP CSP, codehs intro programming, codehs student exercises, codehs canvas
EventssetMouseMoveMethod codehs, mouse event javascript canvas, event-driven programming beginners, mousemove handler javascript
Canvas ObjectsgetCenter codehs, setPosition javascript object, removeAll codehs canvas, drawLine codehs, Circle object codehs
Distance & Mathdistance formula javascript, pythagorean theorem code, Math.sqrt javascript, euclidean distance canvas, calculate distance two points js
OOP Conceptscodehs dog class, codehs leash class, object reference java, instance variables constructor, class composition oop, object passing constructor javascript
Animation LogicsetTimer codehs javascript, animation loop canvas, real-time object tracking, smooth movement javascript, canvas redraw loop
Debuggingcanvas trail artifact bug, codehs removeAll not working, undefined not a function codehs, getCenter returns undefined, codehs mouse event not firing
Learning Intentcodehs 9.7.4 step by step, understand not copy codehs, codehs exercise explained, how to solve codehs leash, codehs walkthrough
Related Lessonscodehs 9.7 assignment, codehs unit 9 quiz, codehs graphics exercises, codehs animation games unit, codehs object follow

13 Frequently Asked Questions

Q
What exactly happens in the 9.7.4 Leash CodeHS exercise?
A
The exercise teaches you to make one object follow another using either mouse events on a canvas (JavaScript version) or object references inside a class (OOP version). In both cases, the "leash" is the mechanism that creates and enforces the relationship between the two objects.
Q
Why does my canvas show trails even after I draw the ball again?
A
You're not calling removeAll() before redrawing. Every time the mouse moves, you must clear the entire canvas first, then re-add every object you want visible. Skipping the clear step means each frame layers on top of the previous one — producing visible trails.
Q
Is the 9.7.4 Leash in JavaScript or Java?
A
Both exist. The JavaScript canvas version appears in the CodeHS JavaScript Fundamentals and Intro to CS tracks. The class-based OOP version with Dog and Leash classes appears in Java-focused courses including AP CS A paths. Check which course you're enrolled in to confirm your version.
Q
How do I get the center of a ball in CodeHS?
A
Call ball.getCenter(). This returns a Point object — not a number. Store it in a variable: var c = ball.getCenter(); Then use c.x for the horizontal center and c.y for the vertical center separately.
Q
Why does my leash line connect to the wrong point?
A
The most common cause is using ball.getX() and ball.getY() instead of ball.getCenter(). The getX() and getY() methods return the top-left corner of the object's bounding box, not its center. Use getCenter() for line endpoints.
Q
What does this. do in a JavaScript class constructor?
A
this. binds a variable to the specific instance of the class being created. Without it, the assignment creates a local variable that disappears when the constructor finishes. With it, the value is permanently stored on the object and accessible from any method inside the class.
Q
How do I calculate distance between the mouse and the ball?
A
Use the Pythagorean theorem: Math.sqrt((mouseX - ballX) * (mouseX - ballX) + (mouseY - ballY) * (mouseY - ballY)). Get the ball's center first using getCenter(), then use those x and y values in the formula alongside the mouse coordinates from e.getX() and e.getY().
Q
Why should I understand this instead of just copying the answer?
A
Unit 9's later exercises — including the full game project — build directly on the leash concepts. Students who copy 9.7.4 consistently get stuck on 9.8 and 9.9, which require the same mouse event and object-following logic applied in more complex ways. Understanding now saves hours of confusion later.
Q
What unit number is the Leash exercise in CodeHS?
A
It is Lesson 9.7.4 inside Unit 9 — Animation and Games. The "9" indicates Unit 9, the "7" indicates Section 7 within that unit, and the "4" is the fourth specific exercise in that section. It follows lessons on basic graphics, timers, and event handlers.
Q
Can I add multiple balls on a leash in this exercise?
A
The base exercise requires one. But once you understand the core logic, extending it to multiple followers is straightforward — create an array of balls, loop through them in the handler, and apply the same distance-check and redraw logic to each one. This is excellent practice for the game unit ahead.

14 Conclusion

The CodeHS 9.7.4 Leash exercise teaches a pattern you'll use throughout your entire programming career: a leader, a follower, and a rule that governs their relationship. That's all it is.

Whether you're building the JavaScript canvas version with mouse events and distance math, or the OOP version with Dog and Leash classes and object composition, the thinking is the same. Define the three characters. Write the constraint. Update continuously. Verify your output.

Close this guide, open CodeHS, and build it yourself — one line at a time. That's the only way the concept actually sticks.