If you console.log() when you debug, you’re doing it wrong. There’s an easier way and it’s right in the palm of your browser.
Sound familiar?
Javascript is the most popular programming language according to StackOverflow’s 2019 survey. If you develop with Javascript, you’ve most likely came across a situation where you had to fix a bug or two.
“No problem!” you say to your rubber ducky, let’s reproduce the bug and fix it with console.log()
. Now, what if I told you that this is not the best practice?
At the end of this article, I included a TL;DR summary.
Console logging works, but there’s a better way.
Instead of console.logging and restarting every time you want to debug, you can instead use Chrome DevTools (right click + inspect).
Perhaps you’re already using it to view and modify HTML/CSS elements, monitor console logs, and measure network performance. But did you know that Chrome has a powerful built in debugging feature where you can:
- view source code
- set breakpoints
- step into, step over, and step out
The rest of the article is a step by step guide on how to use Chrome’s debugging feature with Angular — but feel free to follow along with your existing projects on any javascript frontend framework.
Setting up your environment.
NOTE: If you already have an existing project, skip to the next section.
In this section, we will quickly set up an Angular app using their official guide.
Prerequisites
Node.js version 10.9.0 or later.
Step 1. Install Angular CLI
npm install -g @angular/cli
Step 2: Create a workspace and initial application
ng new my-app
Step 3: Run the application
cd my-app
ng serve --open
This will open your browser to the url localhost:4200
Create the bug 🐛
For the purposes of this demonstration, let’s create a bug and then debug it ;).
Open your favorite text editor and navigate to src/app/app.component.ts
Replace the lines with the following and save.
Look at the browser again and you should see a bug!
[object Object] is simply the default return value when converting a POJO (plain old javascript object) to a string. This is not a desired outcome — so let’s fix it!
Debug Mode 🔴
1. Inspect the sources
Using Chrome, right click > inspect > sources > cmd + p > search file
If done correctly, this will take you to the source code, where the bug lurks.
2. Set breakpoints
Setting breakpoints is vital to debugging effectively. A breakpoint is an intentional pause in a program, which allows the developer to inspect the internal state of the application at that moment. You can use it to view variables and perform other debugging functions.
A breakpoint is an intentional pause in a program, which allows the developer to inspect the internal state of the application at that moment.
To set a breakpoint, click the line number where you want the program to pause. In the example below, we set it at line 9.
Refresh the browser and you should see “Paused in debugger”.
Hover your mouse over the variable author— it should be undefined. The reason that it’s undefined is because the program hasn’t reached this line yet. It finished executing line 8 and is about to reach line 9.
Press ▶️ to continue execution.
3. Step into, step over, and step out.
These basic 3 steps is the bread and butter for debugging.
- Step into is when the debugger steps into or inside a function
- Step over is when the debugger steps to the next line
- Step out is when the debugger steps outside the current function
Refresh the browser again and once the debugger pauses at your breakpoint, step into the function using the panel on the right hand side. This will take you to the function getAuthor()
. Hover your mouse over obj and you will see undefined since we haven’t actually executed it yet. Step over to execute the line and hover your mouse over obj again. This time, you should see a POJO. Step out to return to the caller and now this time author is no longer undefined.
Great — so we now know that author object has value. How do we fix it?
4. Fix the bug
Replace line 10 with the following and save.
title =
my-app by ${this.author.name};
5. Deactivate breakpoints
Click Deactivate breakpoints. It changes blue to indicate that it’s active. While this is set, DevTools ignores any breakpoints you’ve set.
Refresh the page.
Fixed!
Closing
Congratulations! You now know how to use Chrome DevTools to debug efficiently. While console.log()
does have a place in programming, it’s limited to modifying the source code, restarting the program, and nonstop execution. Chrome’s built in debugging tool addresses these disadvantages and offers you the ability to stop, inspect, and investigate what’s happening in the program at the specific point in time.
TL;DR
Open inspector, click the Sources tab, and CMD + P
to view your source code and set breakpoints.
For more information, check out Google’s blog on this topic.
Thanks for reading! Originally published on Faun.
Top comments (38)
Please edit « you are doing it wrong ». There is no « right » or « wrong » way to do it. This is a matter of preference. Both of the methods have pros and cons and it is unfair to declare
console.log()
wrong.Thanks for reading Sebastien!
Perhaps the better word instead of wrong is inefficient.
Quoting Google:
The console.log() method may get the job done, but breakpoints can get it done faster. A breakpoint lets you pause your code in the middle of its execution, and examine all values at that moment in time. Breakpoints have a few advantages over the console.log() method:
In short, breakpoints can help you find and fix bugs faster than the console.log() method.
I like using both. DevTools for more complex debugging where I want to understand the flow of my program. Console log for quick outputs of any variable that I want to see after I modify it. I don't have to go in and manually set a breakpoint and waste time stepping in and out and hovering over variables with my mouse to see what they are.
The console logging functions have their place and for some tasks they are WAY more efficient than the debugger. For straight-up simple bugs and logic errors, yes, breakpoints and the debugger are key tools, but I definitely support the view expressed here that the title of this article is seriously flawed, along with the any suggestion that the console functions should in general be avoided, or are in some way inefficient. Generalizations like that should not be made.
Each approach is useful, and can be the most efficient, depending on the circumstance. Your article reads like "Don't use screwdrivers -- hammers are always more efficient." I find it misleading and poor advice, especially for novice developers who are clearly the target audience of the article.
I think the message is getting lost in this, and if the article and title was more like "If you use console.log to debug, here's another tool you'll want to add to your toolkit", it would be received a lot better.
Considering the fact that you have to go in chrome to find the sources and add breakpoints I find both ways to be the same in terms of what is fast.
Breakpoints or console.log, it is a matter of what you are debugging.
You can write an article about the pros of
console.log()
but I don't think it's unfair to say that using one technique or the other is right or wrong.Have you ever tried stepping through a breakpoint thousands of times, watching a trend over time? Have you ever tried copying the data from a watch into a text document to be uploaded for analysis?
Console.log() is plenty useful. Any time you need to preserve a history over time it's leagues better than anything available in devtools.
Yes, if a developer is unaware of browser debuggers, that developer is definitely missing out, but there are plenty of reasons to use Console.log().
Completely agree. Also,
console.table
andconsole.time
can be quite handy.However, I do hope that people are aware that the simple
console.log
can be set trough devtools as well. Quite often, there is no need to add it to your source directly.(click right on the line number in chrome devtools and select
add logpoint
)Thanks for reading Nate!
I love your response. These are definitely great use cases for
console.log()
.Yes this article is meant to shed more light on browser debuggers. I met quite a few of developers who are unaware of devtools and spend the majority of their time console.logging =/
Another way of achieving this without searching through the source in the browser is, in your editor, to type:
debugger;
at whatever point in the code you want to step into.
e.g.
(though, don't forget to remove any debugger lines you've added after you've finished debugging!)
Breakpoint can be disabled or attached with some condition. There is no way to control
debugger;
. To me it has some value only in case if you have access to source code but browser executes minified code(without source maps) so it's really hard to find appropriate line to put breakpoint.The discussion was about whether or not to use console.log (where you need to be working with source code anyway) so debugger is a useful alternative in this case. For a production build, it would be common practice to minify and uglify the code - stripping out all console logging and 'debugger' statements. So, in that regard, yes, you are correct - this would not apply to a production build scenario.
Obviously, your tools and approaches will vary according to the situation. It's helpful to be aware of all approaches and use as you see fit.
Thanks for reading and sharing another alternative Kyle!
I had no idea about this feature.
I just tried it and it automatically brought me to the
debugger;
breakpoint in devtools. 👍wow! Thank you for this tip!
And, as it often happens in life... 2 hours after reading your comment, I stumble on this tweet:
I simply console.trace()
I don't think you can make a prescriptive argument about how someone should use dev-tools over console.log without covering conditional breakpoints (right click on the breakpoint to edit expression) then the breakpoint will only stop the execution when it matches.
Logging to debug is often used to evaluate the state of things that rapidly change, which you wouldn't be able to use a breakpoint alone for, but with conditional breakpoints it's quite easy to debug these kinds of situations.
I use a combination of all of these debug tools depending on the task.
Thanks for reading Brant!
I love your points. Conditional breakpoint is a great tool indeed, but I felt that it was a bit too advance for this introductory article.
For those who want to a dig a little deeper into the advance features for each breakpoint types, check out this guide by Google.
I use break points, but after hitting the breakpoint i use console to do my debugging. I can test what command will work in the command right away instead of making change, reloading and waiting for the breakpoint. This helps me save lot of time.
Thanks for reading Hari!
Yes I do the same. This is one of the most effective ways to debug and fix issues.
Love your response. 👏👏
I'm gonna go a bit against the grain here and say that I agree. I too think
console.log
is wrong. In my opinion,console.*
methods should never be in a commit (except when commiting a logger class).Not wrong to use it while debugging local, but logging isn't very useful when you have to scroll through pages filled with various other developers' logs. One have to remember to remove those debugging lines before commiting. If you use chrome debugger instead, you don't need to remember.
If you need
console.*
for debugging in a production environment, it should be wrapped in a logger class that can easily be toggled on/off for that environment. Even better if it can toggle where the log entries should be sent (a file, a network request, etc) and toggle severity level.In C# i usually used log4net for that kind of stuff. As a devops I got a bit annoyed when my co-workers built their own logger classes (in a project that had log4net already) just to output to their own logfile. I found multiple log files taking up more and more space on a production server. They each created their own logger classes. And they copied that code into a shared dll too, making it even harder to get rid of.
But, like everything, it always depend on the scope and requirement of the project, of course.
Sometimes a quick console.log is faster
console.log
is useful.Specially if you can't stop the code execution with breakpoints because you are debugging async code, or when you need to print some info in the console often and you don't want stop the code execution each time.
Thanks for reading Antonio!
On the contrary,
console.log()
is actually not useful for async functions since it is non-blocking i.e. the result would be pending. If you want to console.log() async code, you would have to either precede the method with await or chain it with then. In this scenario, a breakpoint would be more efficient.For readers who are unaware:
Nevertheless, I do agree that printing some info into the console without stopping the code execution each time is useful depending on the situation.
The debugger is great in the browser, but there’s nothing wrong with using
console.log(...)
. You can also use Log Points. As well, you can use the browser’s remote debugger to enable debugging in tools like VS Code.Some comments may only be visible to logged-in visitors. Sign in to view all comments.