Debugging is the process of identifying errors in your code the prevent your code from running in the way that you assume and we refer to diagnosed problem code as a bug.
Fun Fact: In 1947, Grace Hopper recorded the first known bug after discovering an actual moth in a relay that caused the Harvard Mark II computer to fail to process.
These errors can be of many different types and can derive from introducing new code in an unsuspecting way. Here is a list of debugging techniques to help resolve bugs in your code.
After introducing a new bug into your code and running your code you will receive some error output in the console. This output can initially be very scary but the truth is it's super helpful to resolve your bug. It will help to identify the type of bug and where it has been detected in your code.
// This error code points to a variable that is referenced incorrectly ReferenceError: i is not defined at Object.<anonymous> (/Users/code/file.js:5:15) // This error line points to line 5 of code in file.js where the error was found in execution => ex: file.js:5:15 at Object.<anonymous> (/Users/code/file.js:5:15)
The next best plan of action is to re-reread your code in the area where the bug has been identified. Quite often a bug is introduced by a simple syntax error that can be corrected with a quick review of the code you recently wrote.
The is a great opportunity to test the sanity of inputs in the functions of your code. Try new inputs to see if they will reproduce the same errors.
You can use print statements in your code like console.log() to reveal return values in your code that are otherwise hidden in implementation.
Break up your code into smaller parts in order to better zero in on problem errors in your code.
learn this technique: single-responsibility principle
After too much deep work and difficult problem solving, your brain tends to get bogged down, and bogged down brains introduce bugs plus make it hard to recognize bugs. Take a break from looking at your screen and take a walk so you can return with a fresh perspective.
The best defense is a good offense. For several languages, there exist automated testing frameworks that prevent many bugs in your code by providing a chance to write tests that provide expected outputs for units of code and domain-specific language to guide you to writing bug-free code.
After struggling with bugs for too long, the best course of action is to seek help from a community that can provide a second set of eyes and a new perspective. This can include a pair-programmer with a friend/co-worker, posting code in a forum like StackOverflow, or solicit advice from any group of people with experience with similar coding bugs.
These are great tips to get you started locating and squashing bugs in your code. I hope this helps you to save tons of development time. If you enjoyed this post feel free to leave a comment about your thoughts and experiences debugging your code.