Programming fundamentals
How to Debug Code Systematically: A Repeatable Method
Systematic debugging means turning a vague failure into a small, repeatable one, forming a specific guess about the cause, and testing that guess instead of changing code at random. Follow the loop of reproduce, narrow, hypothesise, test, fix and protect, and most bugs become a matter of steady elimination.
By CodingMarble · Published · 5 min read

Debugging is a loop, not a hunch
Many developers debug by changing something and seeing if the problem goes away. That works for trivial slips, but on a harder bug it burns hours and sometimes hides the problem without fixing it. The alternative is to treat the bug as a small scientific question. You observe a failure, you propose a cause that would explain it, you design a check that would prove the cause wrong, and you run the check. Each pass either removes a possibility or confirms one.
The loop has six steps: reproduce the failure, narrow the area, form a hypothesis, test the hypothesis, fix the cause rather than the symptom, and add a test so the bug cannot quietly return. The next sections take them in order, then cover tools and the bug families that account for a large share of everyday failures.
Reproduce it, then make it smaller
If you cannot trigger the bug on demand, you cannot know whether you fixed it. Start by writing down the exact steps, the input, the browser or runtime version and the account or data involved. Then strip away everything that is not needed. Remove features, hardcode inputs, delete unrelated components, until you have the smallest case that still fails. This is called a minimal reproduction, and it often reveals the cause on its own: the moment a removed piece makes the failure disappear, you have found a suspect.
Narrowing works in space and in time. In space, use a binary search through the code: put a log or breakpoint in the middle of the flow and check whether the data is already wrong there. If yes, the fault is earlier. If no, it is later. Each check halves the area you must read. For bugs that appeared recently, the same halving works through history, which is what git bisect automates.
Reading a stack trace
A stack trace lists the chain of function calls that were active when the error was thrown. Read the first line first, because it holds the error type and message. Then find the first frame that points into your own code, not into a library or the runtime, since that is usually the nearest place you can act. Frames below it show how execution got there.
TypeError: Cannot read properties of undefined (reading 'email')
at formatContact (/app/src/contacts.js:14:23)
at /app/src/routes.js:52:18
at Array.map (<anonymous>)
at listContacts (/app/src/routes.js:51:30)The message says something was undefined when the code tried to read email from it. The top frame says line 14 of contacts.js, column 23, so that is where to look first. Then ask the real question: not why did it crash here, but why was this value undefined when it arrived. The answer is usually one or two frames down, in the code that produced or passed the value. The same kind of reasoning applies to browser console errors, where the file and line link opens the source.
Form a hypothesis, then try to break it
A hypothesis is a specific sentence of the form the bug happens because X, so if I check Y I should see Z. For example: the contact is undefined because the API returns an empty list for new accounts, so logging the response for a new account should show an empty array. A good hypothesis predicts something you can observe cheaply. A bad one, such as something is wrong with the data, cannot be tested.
Then test it in the least invasive way. Logging prints values at chosen points and works everywhere, including servers and production-like environments, but it needs you to guess where to look and it leaves clutter. A debugger lets you pause at a line, inspect every variable, and step forward, which is far better when you do not yet know which value is wrong. Use logs for flows across services and time, and the debugger for understanding one tricky stretch of code. Change only one thing at a time, otherwise you will not know which change mattered.
Rubber duck debugging is a legitimate tool for the moments when the hypothesis list runs dry. Explain the code line by line, out loud or in writing, to a person or an object. Forcing yourself to articulate what each line is supposed to do often exposes the line that does not do it. Writing the question for a colleague serves the same purpose, and frequently you solve it before sending.
Finding the change that broke it with git bisect
If something worked last week and fails now, the cause is in a commit between the two. Git bisect performs a binary search over those commits. You mark one good commit and one bad commit, git checks out the middle, you test and report, and after a handful of rounds it names the first bad commit. For a range of a thousand commits that is roughly ten tests.
git bisect start
git bisect bad # the current commit fails
git bisect good v1.4.0 # a tag or hash known to work
# Git checks out a middle commit. Test it, then report:
git bisect good # or: git bisect bad
# Automate it: the script exits 0 for good, non-zero for bad
git bisect run npm test
# When finished, return to where you were
git bisect resetBisect only works if each commit can be built and tested, so small, working commits make it far more useful. When the culprit commit is large, you still gain a lot, because the search area shrinks from the whole history to one change.
Common bug families worth checking early
Many bugs repeat familiar shapes, and recognising the shape gives you a first hypothesis for free.
- Off-by-one errors: loops that run one time too many or too few, slices that include or exclude an end index, and mixing zero-based indexes with counts. Test with an empty list, a one-item list and the exact boundary.
- Async ordering: code that assumes one step finished before another. A missing await, a callback that fires later than expected, or two requests whose responses arrive in a different order than they were sent. Log timestamps and check the order.
- Shared state mutation: a function changes an object that another part of the program also holds. Array methods like sort and splice change the original array. Copy before changing, or check whether two variables point to the same object.
- Environment differences: it works on your machine but not on the server. Compare runtime versions, environment variables, file path case sensitivity, time zones, locale settings and the data in the database.
- Stale or cached data: the code is right but you are looking at an old build, an old browser cache or an old record. Do a hard reload, clear the build output and confirm which version is running.
Fix the cause, then protect it with a test
When the hypothesis holds, resist the quick patch that hides the symptom, such as wrapping the line in a try and catch or adding a null check where the null should never have arrived. Ask where the bad value was born and correct it there. Then write a test that fails on the old code and passes on the new, using the minimal reproduction you built earlier. That test is the permanent record of the bug and the reason it will not return silently.
Practical tip: keep a short debugging log while you work, with the hypothesis, the check you ran and the result. When a bug takes more than an hour, the log stops you repeating checks you already did, and it makes a useful description if you need to ask someone for help.
Finally, take one minute to ask why the bug got through, whether a missing validation, an unclear name or a gap in tests allowed it. Small preventive changes after each bug make the next one less likely.
Keep reading
- AI promptsAI Prompts for Debugging Code: 7 Templates That WorkA debugging prompt works when it gives the assistant the error, the code involved, what you expected and what you tried, and then asks for a specific kind of help. Use the templates below as starting points, treat every answer as a hypothesis to test, and never paste secrets into a prompt.
- AI and developer toolsDebug With AI Without Leaking Secrets or Customer DataYou can debug with an AI assistant safely by pasting only a small, redacted, reproducible example and never anything that grants access, such as keys, tokens or connection strings. If a secret does leave your machine, treat it as compromised and rotate it immediately instead of hoping nobody saw it.
- Error fixesFix 'Cannot read properties of undefined' in JavaScriptJavaScript tried to read a property on a value that is undefined, so something earlier in the chain did not hold the data you assumed. Read the property name in the message to find which access failed, then work out why the value was missing: data not loaded yet, a different API shape, or an index that does not exist.
- Interview questions and cheat sheetsGit Commands Cheat Sheet by TaskThis Git cheat sheet is organised by what you are trying to do, with copy-ready commands and a clear label on every command that can destroy work. It ends with the reflog, which is how most lost commits get back.
Need this built properly for your business?
CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.