Debugging JavaScript can feel like trying to find a niddle in the haystack. It’s always frustrating and often headache-inducing. Are you agreeing with me? ๐ But don’t worry! In this post, I am going to explain five effective and essential JavaScript debugging techniques that will not only make your life easier but surely help you to enjoy JS code debugging. Yes, really! ๐ฆธโโ๏ธ๐ป
1. Master the Console Like a Pro (No, Not the Gaming One ๐ฎ)
We all love console.log(), but the console has some hidden features that can save your debug time dramatically.
- console.error(): Logs errors in red, because your mistakes need to identify easily right?
- console.warn(): Gives you gentle reminders, like a friend telling you to double-check your JS code.
- console.table(): Plot your arrays or objects data into a beautiful table. It’s great for erroneous data visualization.
console.group()
/console.groupEnd()
: Organizes logs into collapsible groups, so your console doesnโt look like a chaotic mess.
Example:
const pets = [
{ name: 'Fluffy', type: 'Cat' },
{ name: 'Rex', type: 'Dog' }
];
console.table(pets);
console.error('This is an error message');
console.warn('This is a warning message');
console.group('Pet Details');
console.log('Pet 1:', pets[0]);
console.log('Pet 2:', pets[1]);
console.groupEnd();

2. Set Breakpoints and Step Through Code (Like a Time Traveler ๐)
Using console.log()
everywhere? Thatโs from 2010! Breakpoints facilitate you to pause your code in the middle of execution and inspect everything.
- Open Chrome DevTools (
Ctrl + Shift + I
orCmd + Option + I
). - Go to the Sources tab.
- Click the line number where you want to pause the code.
Refresh your page, and boom! Your code stops right there. You can now:
- Step through functions one line at a time.
- Look quickly into variables.
- Understand your appโs flow without spamming
console.log()
.
Example:
function calculateTotal(price, tax) {
let total = price + tax;
return total;
}
let finalAmount = calculateTotal(100, 20);
console.log('Final Amount:', finalAmount);

3. Use the Network Tab for API Debugging (Because APIs Love Drama ๐ญ)
When your API isnโt playing nice, the Network tab is your best friend. Don’t believe? Let’s check.
- Monitor every API call โ success or fail.
- Inspect request/response headers, payloads, and status codes.
- Replay failed requests to debug without refreshing the page.
Example:
fetch('https://api.example.com/pets')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Oops! Something went wrong:', error));

4. Watch Variables and Expressions (Become a Code Detective ๐ต๏ธโโ๏ธ)
You can use the Watch panel of Chrome DevTools. I mean, monitorโyour variables.
- Track specific variables and your complex expressions always.
- See how values change as you step through your code.
- Avoid spamming
console.log()
just to see ifuser.name
is still undefined. ๐
Example:
let user = { name: 'John', age: 30 };
function updateUserAge(user, newAge) {
user.age = newAge;
return user;
}
updateUserAge(user, 31);
console.log(user);

5. Leverage Linters and Formatters (Because Ugly Code is a Crime ๐)
Messy code hides bugs. Linters like ESLint catch issues before they cause trouble, and formatters like Prettier make your code beautiful.
- ESLint: Spots syntax errors, bad practices, and even dad jokes (okay, maybe not).
- Prettier: Auto-formats your code, so it looks like it was written by a perfectionist.
Setting up ESLint:
npm install eslint --save-dev
npx eslint --init
Example with ESLint and Prettier:
function sayHello(name) {
console.log('Hello, ' + name);
}
sayHello('World');
๐ Quick Summary Table
Technique | Purpose | Example Code Snippet |
---|---|---|
Console Methods | Log and organize data in the console | console.table(pets) |
Breakpoints | Pause code and inspect execution | calculateTotal(100, 20) |
Network Tab | Monitor and debug API calls | fetch('https://api.example.com/pets') |
Watch Variables | Track and observe variable changes | updateUserAge(user, 31) |
Linters & Formatters | Improve code quality and readability | npm install eslint --save-dev |
๐ Conclusion (You Made It! ๐)
Debugging doesnโt have to be complex. No more!! With these techniques, youโll:
- Spend less time hunting bugs.
- Feel like a JavaScript wizard. ๐งโโ๏ธ
- Build apps that actually work.
Which of these debugging tips will you try first? Or do you have a hilarious debugging story? Share it in the comments โ we love those! ๐ฌ๐
Happy coding and may your bugs be few and your console logs be meaningful! ๐โจ
๐๏ธโโ๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐ฅ Asp.net C# Developer
๐ Solution Architect
๐จโโ๏ธ Database Administrator
๐ข Speaker
๐ MCTS since 2009
Leave a Reply