DEV Community

Cover image for Stop Console.Logging! This is How to Use Chrome to Debug JavaScript

Stop Console.Logging! This is How to Use Chrome to Debug JavaScript

songthamtung on October 03, 2019

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 famil...
Collapse
 
smonff profile image
🌌 Sébastien Feugère ☔

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.

Collapse
 
songthamtung profile image
songthamtung

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:

With console.log(), you need to manually open the source code, find the relevant code, insert the console.log() statements, and then reload the page in order to see the messages in the Console. With breakpoints, you can pause on the relevant code without even knowing how the code is structured.

In your console.log() statements you need to explicitly specify each value that you want to inspect. With breakpoints, DevTools shows you the values of all variables at that moment in time. Sometimes there are variables affecting your code that you're not even aware of.

In short, breakpoints can help you find and fix bugs faster than the console.log() method.

Collapse
 
nirmpate profile image
Nirmal Patel

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.

Collapse
 
appurist profile image
Paul / Appurist • Edited

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.

Collapse
 
avpaul profile image
Paul Abimana

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.

Collapse
 
jafuentest profile image
Juan A. Fuentest Torcat

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.

Collapse
 
natejgardner profile image
Nate Gardner

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().

Collapse
 
smeijer profile image
Stephan Meijer

Completely agree. Also, console.table and console.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)

Collapse
 
songthamtung profile image
songthamtung

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 =/

Collapse
 
ky1e_s profile image
Kyle Stephens • Edited

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.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  author = getAuthor();
  debugger; // <-- here
  title = `my-app by ${this.author}`;
}

function getAuthor() {
  const obj = { name: 'songthamtung' };
  return obj;
}

(though, don't forget to remove any debugger lines you've added after you've finished debugging!)

Collapse
 
skyboyer profile image
Yevhen Kozlov

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.

Collapse
 
ky1e_s profile image
Kyle Stephens • Edited

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.

Collapse
 
songthamtung profile image
songthamtung

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. 👍

Collapse
 
pixeline profile image
Alexandre Plennevaux

wow! Thank you for this tip!
And, as it often happens in life... 2 hours after reading your comment, I stumble on this tweet:

Collapse
 
abhikhatri profile image
Abhi Khatri

I simply console.trace()

Collapse
 
brantwedel profile image
Brant Wedel • Edited

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.

Collapse
 
skyboyer profile image
Yevhen Kozlov

which you wouldn't be able to use a breakpoint alone for
devtools provide you with "logpoint" and also you may create breakpoint with condition like console.log(someData),false. So breakpoint is self-sufficient tool for debuggin

Collapse
 
songthamtung profile image
songthamtung

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.

Collapse
 
hari2m profile image
Hari Krishna Gaddipati

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.

Collapse
 
songthamtung profile image
songthamtung

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. 👏👏

Collapse
 
emptyother profile image
emptyother

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.

Collapse
 
bilalsaeed232 profile image
Bilal Saeed

Sometimes a quick console.log is faster

Collapse
 
salvan13 profile image
Antonio Salvati 🦊

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.

Collapse
 
songthamtung profile image
songthamtung

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:

An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.

Nevertheless, I do agree that printing some info into the console without stopping the code execution each time is useful depending on the situation.

Collapse
 
nickytonline profile image
Nick Taylor • Edited

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.

Collapse
 
calebcauthon_14 profile image
calebcauthon

the title is clickbait. in the summary it says

While console.log() does have a place in programming

thanks for sharing! chrome is so good for debugging.

Collapse
 
braxnu profile image
Karol Baczewski

As others said, console.log has some solid advantages over the debugger. The top one is that it gives you insight into code execution without interfering with timeouts and the execution timing in general. These things matter a lot in asynchronous world. Saying "stop using ..." is misleading.

Collapse
 
guyinpv profile image
Zack

One of the problems I have debugging in the browser is how to skip stepping into other files. If I want to debug only a particular script, I don't want to have to step out into jQuery files and every other random JS file loaded, if I'm just trying to tshoot one file.

I know there is a way to ignore some files, or maybe that was another browser, or another time? Last few times I tried to find a way to ignore certain files when stepping through code, I couldn't find it in Chrome.

Collapse
 
songthamtung profile image
songthamtung

Thanks for reading Zack!

I encounter the same issue and what I typically do is to place breakpoints in the relevant code and press 'play' if it gets into random JS files.

Collapse
 
artoodeeto profile image
aRtoo

or you can use vscode and run chrome debugger and set breakpoints directly into vscode. much easier.

Collapse
 
bendem profile image
bendem • Edited

Maybe you should mention the fact that you can add logging without console.log?

Collapse
 
skyboyer profile image
Yevhen Kozlov

indeed. eventually it works even with older Dev Tools: just running conditional breakpoint with condition like console.log(data), false(,false will return false so condition will never stop execution)

Collapse
 
academyaquarius profile image
Aquarius.Academy

No one has ever said: "and fix it with console.log()".

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I console.table

Just kidding I use both because it's not always available with source maps.