r/javascript • • Nov 04 '18

Basics: How to stop using console.log() and start using your browser’s debugger

https://medium.com/datadriveninvestor/stopping-using-console-log-and-start-using-your-browsers-debugger-62bc893d93ff
351 Upvotes

127 comments sorted by

12

u/eyememine Nov 04 '18

I really like medium.com but their fucking nav bar or whatever at the top of the page drives me nuts, waaayyy too big. Especially weird since I only read web dev stuff on there

5

u/Doomenate Nov 04 '18

I have a chrome extension called "Fuck It" that lets me right click and remove elements from a website. I do that every time I read a medium article

1

u/eyememine Nov 04 '18

Hmm interesting. I'm mainly annoyed by it on mobile though, anything for that?

1

u/Noctis_Lightning Nov 05 '18

Not entirely sure but see if the extension is available in Firefox. Firefox let's you use extensions on mobile (at least on android idk about iOS)

-5

u/fagnerbrack Nov 04 '18

Download the app, it's better

0

u/[deleted] Nov 05 '18

[deleted]

0

u/fagnerbrack Nov 05 '18

Are you mad, bro?

3

u/wishinghand Nov 05 '18

There's an extension called "Make Medium Readable Again" that I use to get rid of it.

457

u/[deleted] Nov 04 '18

you can pry my console.log from my cold dead hands

198

u/ikeif Nov 04 '18

There was a quote posted last time something similar was posted, along the lines of "what my CS professor told me" (I'm paraphrasing from memory as my search is failing to find it):

A beginner developer relies on console.log, the intermediate developer uses the debugger, and the expert developer uses console.log.

63

u/r0ck0 Nov 04 '18

Yeah I found fiddling around with breakpoints and stepping through debuggers to be tedious compared to just logging a lot of the time. It's a bit like comparing a GUI vs CLI.

Different tasks suit one or the other better. But often the CLI/logging is just less fiddly and frustrating.

I'll still use an interactive debugger for certain issues, but often just typing a few lines for logging is quicker and takes less distracting thought.

13

u/trwolfe13 Nov 05 '18

Especially when Chrome has a bug in its developer tools that causes breakpoints to not always be hit.

3

u/vtesterlwg Nov 05 '18

or firefox

4

u/trwolfe13 Nov 05 '18

I would, but our client’s corporate policy dictates that we can only use Chrome and Edge. We have to submit support tickets any time we want software installed/updated and there’s a lengthy appeals procedure for any software that isn’t already on the approved list.

1

u/vtesterlwg Nov 05 '18

unfortunate lol

3

u/CunningFatalist Nov 05 '18

I use the debugger, if the problem at hand is too hard to reason about. But in general, console.log is just fine.

1

u/nschubach Nov 05 '18

Disclaimer: the older I get, the more "keyboard" focused I get.

I find using the debugger to be too mouse intensive. If I can console log something, I can usually just keep my cursor focus in the editor, log out a result set and see what I need. Using the debugger means removing my hands from the home row to the mouse and fiddling with the mouse and various tabs which I find annoying.

I agree though, the debugger is nice to have, but for most things a simple console log is a quick solution.

11

u/[deleted] Nov 05 '18 edited Nov 05 '18

Except the expert is putting the console.log as the statement in a conditional breakpoint in the debugger instead of adding it to the code, saving, reloading. It returns undefined so the breakpoint never pauses execution but it is still executed so you get the output.

1

u/WarPhX Nov 05 '18

Now that's what i call "metal as fuck"

24

u/ParasympatheticBear Nov 04 '18

It’s so true. Logs are simply more productive most of the time.

15

u/Asmor Nov 05 '18

The debugger has its place. Sometimes it's just easier to follow something through because you're not sure where everything's going FUBAR.

But yeah, 99% of the time console.log's faster and easier.

2

u/uttermybiscuit Nov 05 '18

The debugger is a god send when working in node

5

u/rickdg Nov 05 '18

Then there are those who alert for life :)

5

u/[deleted] Nov 05 '18

[removed] — view removed comment

2

u/rickdg Nov 05 '18

I know right, if only there was some way to stop execution inside the context you need so you can investigate any local variable...

1

u/sarkie Nov 05 '18

I usually have to use it for timing issues nowadays.

1

u/amoshydra Nov 05 '18

What meme format is suitable for this quote?

29

u/dweezil22 Nov 04 '18

Console.log will show you were it was logged from, which is huge in unstable code that you're still working through.

17

u/loopsdeer Nov 04 '18 edited Nov 04 '18

I got you a present, don't open it until you're home: (new Error()).stack

Edit: Another hot tip for you lovely people: stack looks like a simple property, but when it is evaluated it will actually incur a performance hit as the code must be paused while the stack is stringified. If you are using this to "tag" a line of code, you can safely save the value in a variable and only reference the variable. This unfortunately won't be helpful if you're really interested in the checking out the stack each call.

14

u/Xeon06 Nov 04 '18

What about console.trace?

7

u/loopsdeer Nov 04 '18

Awesome, thanks! Be wary of this note in trace's spec: Event.stack and console.trace are NOT guaranteed to be the same. https://console.spec.whatwg.org/#trace

2

u/[deleted] Nov 05 '18 edited Nov 05 '18

I wrap all my asynchronous awaitcalls in try/catch to add the local stacktrace to the existing one using that expression. This way I get a full asynchronous stacktrace - at the (annoying) price of having to wrap every single await.

try {
  await myAsyncCall();
} catch (err) {
  err.stack += (new Error()).stack;
  throw err;
}

EDIT: For this to work, if you have a promise returning function to call at the end of your function, you must use return await myFunction() inside such a try/catch or the context wold be lost - it must still be available when the async. function resolves its promise.

JS runtimes should actually be able to do that automatically, because when await is used the function and thereby the location information remains available, unlike async. calls without await where the calling function exits right away. However, no runtime does that yet. I really hope I can get rid of all those wraps some day soon, but until then, having a full async. stack trace is worth it to me.

Now if only uncaught rejected promises would show any indication of which promise was rejected where...

PS: You may have seen or heard that async. stack traces already are available, but that's only true in the debugger (Chrome dev. tools). I want unexpected runtime exceptions that a user reports to me to have that info though!

2

u/loopsdeer Nov 05 '18

Ugh try/catch around await is an insufferable weakness of the design. They baited us with beautiful, concise examples, but we the public did not read the fine print.

I much prefer to directly use Promises for known exceptions inside an async function, because the interface is functional. For example, if instead of return await myFunc() I had return callAndWrapResultInPromise(myFunc) there would only one call site to make your change, the ridiculously named function (which my new framework conveniently saves as window.$)

2

u/[deleted] Nov 05 '18

I must admit I have no idea what your second paragraph says. I only say this because it's a reply to my comment, otherwise I'd of course just say nothing and move on.

1

u/loopsdeer Nov 05 '18

Sorry it was late. That was all to explain my idea: you can write a function that returns a Promise. Then use that function everywhere you now use await (yes you can do this!). Then, to add the cool stack trace construction you did, you'd only have to put that in one place, that function. Hope this helps

2

u/[deleted] Nov 05 '18

I don't understand. You already have to do this exactly only once where it is needed. Or do you mean a wrapper function around async. calls? I tried that, I tried many things, including how stack traces look like when using .catch() instead of try/catch. What resulted in the best stack traces - and across platforms (my particular code needs to run on node.js, react native, browser, a backende library that.. "does stuff") - was this method. At that point I stopped micro-optimizing any further, because it really sucks to do this and I'm really just waiting for runtimes to produce async stack traces on their own (which should be relatively easy when await is used, teh "real async." option probably would/will have considerable runtime cost, in comparison, because it needs to keep track of a stack that's no longer there).

1

u/loopsdeer Nov 05 '18

You said "the annoying price of wrapping every single await". My idea was to mitigate that by creating only one place that had to happen. But as you say, if you tried .catch and it didn't work for you than it's not helpful :-D

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

[removed] — view removed comment

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

How exactly do I lose errors? Please explain your reasoning.

Too much of this can slow down the rendering a lot.

This is backend code, and I already made my choice between traces and efficiency, as I pointed out myself.

Also, did you keep in mind that we are talking about asynchronous code here? There already is delay, usually disk or network. How much additional delay does a try/catch around an async. op cost compared to the cost of the async op itself?

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

[removed] — view removed comment

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

Coming back to

If you use this inside a module with import, it will basically stay quiet for basics errors, like undefined variables.

I don't understand why you think errors are swallowed. Where, how?

Also coming back to the question of how much additional delay does a try/catch around an async. op cost compared to the cost of the async op itself? What does canvas speed have to do with any of it?

I'm confused by the unspecificity of your reply, branching off into more and more general territory and now even into completely different systems. The same syntax can not be compared between different languages. Example: Java, where try/catch is again completely different. Not to mention the difference between try/catch in synchronous vs. asynchronous code. Oh and sure, slow is worse than fast, okay, I agree.

23

u/[deleted] Nov 04 '18 edited Nov 04 '18

Same here, and the issue apart from being used to it and ease of use is that I have a scenario where I have little choice:

I work on a library that performs (bluetooth or network) communication between peers, and if I were to set breakpoints and stop one side there would be timeouts. Even without a timeout, the whole timing would change, I really want the communication to proceed in real time and only collect what's going on in real time (not on the network, packet sniffing is not necessary, in the software) and look at it afterwards.

The debugger is okay when there's only one instance, as soon as there is communication, on the same machine between independent threads or processes, or between machines, it may not work so easily when the behavior changes when one side is stopped in the debugger.

Also, this may sound strange, but for me personally and at least thus far - different people do different things - a debugger gives me too much information. I don't actually want all those stacks and variables, way too much to think about. I prefer looking at the code and run it in my head, and when I want to know something then I add a very specific log statement. Important: First I find out what I actually want to know, I hate getting a dump of all kinds of stuff, to me that's "backwards". I spent the vast majority of my debugging time just looking at code. I only run it, with the specific log statements, after deciding what I want to know. I mostly write backend code though, I don't know if I would see things differently if I were to write frontend code.

11

u/fzammetti Nov 04 '18

I wrote a reply, and before posting it I realized it's saying almost the same as you! I'll post it, since I took the time to write it, but it's pretty much the same thing I think...

There's a benefit to console.log()'ing that using a debugger misses: one consolidated view of what's going on.

What I mean is that sometimes it's really nice - and I would argue more efficient - to have 20 log messages in one place you can read through and spot the issue rather than having to step through the code little by little. Sometimes, that holistic, consolidated view is exactly what you need to solve the problem and the little mental break that occurs when you step through each line of code can actually get in the way.

Plus, stepping through code means that you're focusing on the CODE, which when you're debugging is often times counterproductive. I know that sounds weird, but I'm concerned with what the code is DOING when I'm debugging, not immediately what the code actually is. I need to see the problem before I can solve it, and the code itself rarely matters when you're just trying to see the problem. A debugger forces me to think at the code level whereas console.log() gets me a level above that, which is what I need.

At the end of the day, any article that says or even implies that you should always use a debugger over console.log() - or one that says the exact opposite - is an article to be ignored. Both have their places and uses. Right tool for the job and whatnot. Dismissing one out of hand is folly.

2

u/Abounding Nov 04 '18

While that is true, as far as I'm aware, the only time pausing execution on one machine could become a problem is when there's a race condition.

4

u/[deleted] Nov 04 '18

It changes the whole behavior. For example, my code takes care of sending just enough to minimize how much stuff either side needs to have in memory. It iterates over a graph of objects on disk on each side, and I control the speed of the iteration by feedback from the other side. Without it I'd possibly read waaayyyy ahead and have more and more stuff sitting and waiting in memory that cannot be garbage collected. So, very different behavior. In addition, lots of lower level components have timeouts. The code runs in node.js, low.js, React Native, browser, over websockets or over bluetooth. If I pause for a minute somewhere there's going to be a timeout.

Also, as the other commenter said and I too, sometimes it's just better to debug this way, easier, more logical, better suited for the "flow".

1

u/Abounding Nov 04 '18

Ohhh. I see. Yeah that would make sense actually.

1

u/49Ivories Nov 05 '18

I LOLed at this!

0

u/[deleted] Nov 05 '18

If you like console.log then you'll love this:

// assume we are exporting brokenCode

const logged = new Proxy(brokenCode, {
  // if brokenCode is an object
  get: function (target, property, receiver) {
    console.log(`Getting ${property} with value ${target[property]}`)
    return Reflect.get(...arguments)
  }
  set: function (target, property, value, receiver) {
    console.log(`Setting ${property} to value ${value}; current value is ${target[value]}`)
    return Reflect.set(...arguments)
  }
  construct: function (target, args, receiver) {
    console.log(`Constructing a new brokenCode with args: ${...args}`)
    return Reflect.construct(...arguments)
  }
  // if brokenCode is a function
  apply: function (target, thisArg, args) {
    console.log(`Calling the function with ${...args}`)
    const returnVal = Reflect.apply(...arguments)
    console.log(`It returned ${returnVal}`)
    return returnVal
  }
})
export default logged

3

u/dons90 Nov 05 '18

what am I looking at

1

u/mildfuzz Nov 05 '18

A wrapper that will wrap and object and log when anything is done to the object, be it a function all or access or set a parameter. It seems pretty neat. A factory method to contain this in a scope and set meaningful labels might also be useful.

82

u/Argentumvir Nov 04 '18

Some advice I got once: If you can't easily debug your code with console.log your code is overly complicated and should be simplified

Whether that's true or not is up for debate, but I think there's at least some merit to that school of thought

22

u/phpdevster Nov 04 '18

This is generally true of any code and any debugging. Here's my recommended debugging process:

0. Begin with a philosophy that code exists to make your life easier, not harder. If code is making your life harder, it is bad code and should be replaced with better code.

  1. If debugging some code is hard, stop and take a minute to think about the architecture and how the code was designed. Chances are there is a simpler solution or approach.

  2. If you feel you can safely refactor and simplify the code, do it first, THEN fix the bug.

  3. If there is too much regression risk, create technical debt ticket with as much detail as possible, and mark it in the code, and then record an estimate of how much time it took you to fix the bug because of its poor design. Add that info to the ticket.

  4. If your organization doesn't have the notion of technical debt management, start it.

  5. If they shoot you down, look for a new job.

2

u/[deleted] Nov 04 '18

If code is making your life harder, it is bad code and should be replaced with better code.

Unless it is code that makes your life harder now but much easier later on.

0

u/[deleted] Nov 04 '18

[deleted]

1

u/ParasympatheticBear Nov 04 '18 edited Nov 04 '18

Now I feel dirty reading the list. If log lines turn you on, maybe we can get together sometime for coffee? I can output 5MB of logs per second from my daemon process, and that's with me not trying!

0

u/[deleted] Nov 05 '18

[deleted]

3

u/lulzmachine Nov 04 '18

Yeah. I've had to cut down a lot on my usage of debuggers. Since it causes me to write less tests

2

u/ParasympatheticBear Nov 04 '18

I have never seen code in a higher level language that could not be debugged with logs. Same is not true for the debugger - though mostly for multithreaded environments. Anyway logs are simple to use and work almost universally

0

u/loopsdeer Nov 04 '18

This is a Code Smell. Don't mistake this for necessity. You will need to learn other debugging strategies for networking, other non-determinism, meta-issues like memory leaks, non-accessible legacy code.

-3

u/[deleted] Nov 05 '18

You must really be shit to achieve memory leaks with JS.

5

u/loopsdeer Nov 05 '18

You're mean and incorrect. En garde!

1

u/[deleted] Nov 05 '18

I will have my blade between your eyes in less than 10 second!

This wasn't a you pointed toward YOU, it was a generic you. It's still true that achieving memory leaks in js is a feat of mediocrity.

1

u/loopsdeer Nov 05 '18

Your comment was directed at me directly, because I have made plenty of memory leaks in JS.

I feel yours is an immature opinion. Memory leaks can occur by typos, misunderstanding documentation, misreading code. It's a very easy mistake to make in any language.

If your thinking that JS's garbage collection makes one immune, think again. I might say the complex rules and invisibility of pointers makes it more vulnerable than C, e.g. you can never be certain when GC will run.

So when you say one must be bad to do it, you're just wrong. One must be human to do it.

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

If you're thinking that JS's garbage collection makes one immune, think again.

No, I don't.

So when you say one must be bad to do it, you're just wrong. One must be human to do it.

Well bad dev are humans too, never denied that.

I feel yours is an immature opinion. Memory leaks can occur by typos, misunderstanding documentation, misreading code. It's a very easy mistake to make in any language.

Not understanding something doesn't make this something immature.

Typos usually provoke syntax errors, unless you give similar names to various element, aka shit naming very common in unprofessional code.

Misreading code implies that you don't understand what you use.

Maybe memory leaks are something that comes when you use frameworks ?

1

u/loopsdeer Nov 05 '18

Okay so when I provide a good counter argument and you merely say no, I think you don't have any good arguments and are trolling. Prove me wrong pls and let's actually discuss.

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

Maybe I edited the comment after your posted yours not sure, read again and tell me.

I'm not trolling, the first comment was a low effort reaction yes.

Keeping references and having factories usually eliminate any memory leak.

1

u/loopsdeer Dec 24 '18

Idk how I didn't see this. Thank you for the thoughtful response.

It seems like you have uniquely strong habits when it comes to memory leaks. That makes you good at this. My point was that normal JS devs, of whom I interact with a lot and am one, are susceptible.

Perhaps it is that most JS projects don't deal with huge amounts of objects or long runtimes, and rely on the invisible GC, and so bad habits emerge in the absence of negative feedback.

Regardless, I don't think this makes a JS dev shit, tho most of us would certainly be shit at writing professional CPP out of the gate.

→ More replies (0)

1

u/[deleted] Nov 05 '18

[removed] — view removed comment

1

u/[deleted] Nov 05 '18 edited Nov 05 '18

I ve never used any framework. I'm a C++ dev, Memory error is something I know, I use valg and gdb on a daily basis. Just not in JS (Ajax, webworker, extensive use of event, etc) that I've used for a while now.

1

u/[deleted] Nov 05 '18

[removed] — view removed comment

1

u/[deleted] Nov 05 '18

?

36

u/[deleted] Nov 04 '18

As someone who has worked hard to make the Firefox debugger better, I generally disagree, you can use the two in ways that compliment one another.

4

u/SaabiMeister Nov 05 '18

And you can control the profiler with console.profile()

1

u/worthcoding Nov 05 '18

Thanks! I'm a relative beginner. Do you think this article is a good starting point? Where do you recommend we beginners learn debuggers?

57

u/mildfuzz Nov 04 '18

Second time in as many days I have heard people suggest you should stop using console.log. This is terrible advice.

Yes, learn proper debugging. It is SUPER important. But do not demonise console.log, it's a different tool and is still very useful.

The problem will tell you which tool to use to solve it.

2

u/howMuchCheeseIs2Much Nov 05 '18

To your point ("The problem will tell you which tool to use to solve it"), one of the most compelling advantages of debugging this way is that you can live edit the code in place, in the current state, without reloading the app. Sometimes it takes many more steps than laid out in the example to reproduce a bug, in which case using the debugger is a vast improvement.

2

u/mildfuzz Nov 05 '18

I don't dispute the value of the debugger tools AT ALL. I use them all the time, and they are my go to debugging method. BUT I still want console.log sometimes, and that's fine. We should not demonise developer tools. Console has a lot to offer.

19

u/[deleted] Nov 04 '18

you should not avoid console.log() completely, it is still good for simple tests like if the code had executed or to echo a single variable, it's simple and fast but I agree when it comes to bigger problems, some more sophisticated ways could be done

3

u/jkuhl_prog vue > react; fight me Nov 04 '18

Right, I usually use it real fast when hitting an endpoint just to make sure I set up my promises and async/await correctly.

"Oh it came through, good, now I can start building the component that uses this."

17

u/OkDonkey Nov 05 '18

Gonna be super honest, console.log("here") is way easier than using browser tools.

11

u/mattaugamer Nov 05 '18
console.log('HERE?');
console.log(myVariable);

2

u/OkDonkey Nov 05 '18

You are the chosen one.

2

u/PickledPokute Nov 05 '18

Clicking left of the line number in your editor to toggle a breakpoint is way easier than writing a new line and then possibly recompiling and reloading while usually also losing the current program state.

2

u/dumbdingus Nov 05 '18

That's a disadvantage of compiled js, not of console logging.

1

u/PickledPokute Nov 05 '18

Reloading and losing current program state applies even with uncompelled js.

1

u/dumbdingus Nov 05 '18

You can make changes to uncompiled js without reloading.

1

u/PickledPokute Nov 05 '18

ah, true if browser inspectors are used.

15

u/Jakkc Nov 04 '18

Does anybody else find the debugger a bit jarring to use sometimes? I have to switch to the resources tab, jump through functions, press the resume button, then remember to remove the debugger statement when I'm finished otherwise I go back to step one. It definitely has its uses, but I find the extra few clicks I have to make quite inferior to simply logging a variable in a lot of scenarios.

11

u/vidro3 Nov 05 '18

and then sometimes the debugger jumps into React specific code for what seems like 800 function calls so you just hit 'resume'

2

u/vtesterlwg Nov 05 '18

lol yep its unuseable

7

u/FormerGameDev Nov 04 '18

I would argue that for many cases throwing in a log is far faster than dealing with the debugger functions. If vs codes log point worked predictably it'd go a huge way toward solving almost all of my debugging. It's very rare that I ever need to step code, except when dealing with mocha and it refusing to do something

0

u/[deleted] Nov 04 '18

[deleted]

1

u/vidro3 Nov 05 '18

react chrome dev extensions.

ok been too afraid to ask this for a while: is there an easy way to see what props a component has through React chrome dev extension? seems like I always have to click through a dozen levels of props--> children-->props-->children

4

u/[deleted] Nov 04 '18

The only potential issue with this is that people tend to package and nobody JavaScript files together. Even if you do pretty print in the console it can be a pain to find where you need to debug

3

u/littleviking001 Nov 04 '18

Isn't this what source maps were made to solve?

3

u/[deleted] Nov 04 '18

I think they were primarily meant to deobfuscate/debundlify (is that a word?) production code when there's a need for a readable information on where the error/bug actually occured, etc. So yes, they were designed to simplify debugging, but on a different level.

2

u/MordredKLB Nov 04 '18

I really think it's at all levels. If your toolchain is creating sourcemaps then debugging is a breeze no matter where you're investigating. I use it daily when debugging angular 6 code, and only use console.log if for some reason I can't figure out where I need to set my breakpoints (or I need to easily inspect objects from a stream).

1

u/[deleted] Nov 04 '18

That's true. :) Modern webdev can utilize sourcemaps in many different ways (i.e. we, among other code like JS, use it to get back to SASS when analyzing CSS rules). What I meant was the basic reason they were created to begin with, although it's just my speculations. ;)

1

u/MordredKLB Nov 04 '18

I didn't even know you could go from CSS to SASS :P

2

u/[deleted] Nov 04 '18

It depends on how early in your build process you start monitoring changes for the sourcemaps. We did it in an early stage before SASS got compiled and bundled down to a single CSS file, so with the maps loaded, the browsers show SASS files instead of the generated CSS.

0

u/lulzmachine Nov 04 '18

Yeah but whenever source maps work well, you should rush to buy a lottery ticket. Seems luck is on your side

2

u/PmMeYouBicepsGirl Nov 04 '18

I love the fact that you can edit variables in debugger at runtime, sometimes it really speeds up development/debugging.

2

u/laggingtom Nov 05 '18

Does anyone use any logging libraries on the browser side, similar to Winston in node?

2

u/Null_Ping Nov 05 '18

What if I use JS in a non-browser environment?

1

u/PickledPokute Nov 05 '18

Like a server like node? Hope that they chrome debugging protocol.

For node, run `node --inspect-brk code.js` and connect your chrome or editor to the debug session.

1

u/Null_Ping Nov 05 '18

Thats interesting! Thanks for the tip :)

3

u/Loves_Poetry Nov 04 '18

Great article. The debugging functions in browsers are really useful. Everyone that uses javascript should be using browser debugging tools.

One thing I didn't see the article mention is that when you're working with a larger codebase, you can simply type the name of the function in your console and then click the link that takes you directly to the sources tab and the line of code where that function starts. Then you can set a breakpoint in that function on any line you want. This is especially useful for code that gets loaded into the page later, since this won't show up in the sources tab by default.

1

u/chrismellor08 Nov 05 '18

I recently took over a project where the previous developers hadn't ever used a debugger. It blew my mind. I do use console logs often, but I'm not sure how I could ever manage without constantly being attached to my debugger. I feel like this is something that should be learned and implemented when you are getting your foundations.

1

u/nbapat43 Nov 05 '18

how do you debug GTM tags then?

1

u/Noctis_Lightning Nov 05 '18

I am a beginner been doing this for a year but I've found both to be helpful in different situations.

2

u/vtesterlwg Nov 05 '18

i always use console and never debugger, for ten years lol

1

u/guoyunhe Nov 05 '18

I also feel console.log() is not good. Especially when you have no idea what to log and where to log.

Today, all projects are using webpack or other bundling tools. The JavaScript bundle is huge in my project, 20MB. If I open source in web dev tool, the browser simply freezes...

1

u/crazyfreak316 Nov 05 '18

Another LPT: Use debugger; statements for code that is hard to put breakpoints on. It was especially useful for async code before they improved async debugging in last few versions of chrome.

1

u/[deleted] Nov 07 '18

While it's nice to use proper tools for the job, you'll soon realize that not everything can be debugged with using a debugger instead of console.log.

An example would be any "digestible" JS framework, which runs the refresh cycle few times a second in some cases, like AngularJS/React/insert other here. With a debugger you'll find yourself stoping multiple times on single use-case execution, often not having the certainty that it's the one you want.

Another thing: race conditions (yes, it's possible in an event rich app). The debugger can affect the order of code execution in parallel events, thus masking the race condition itself. You'll never find it this way (sometimes you just need a split second delay for the code to work or not).

console.log in non-blocking, so it's influence on the way the code executes is minimal (if you're not logging tons of things at least). The debugger blocks a part of your code, so you might just miss the issue.

0

u/[deleted] Nov 04 '18

Nice write up. Definitely should help out those just starting out.

0

u/[deleted] Nov 05 '18

[deleted]

1

u/PickledPokute Nov 05 '18

With just async functions there's usually no big problems. Breakpoints work fine, but stepping through awaits might not work as expected.

Unless of course there's some transpiling of async/await which breaks source maps, which babel did at least recently. For those cases I built a special dev version without transform regenerators and debugged the problem there.

0

u/[deleted] Nov 05 '18

[deleted]

2

u/PickledPokute Nov 07 '18

Usually the transpileres are way too conservative. If you have a problem you want to debug, then most likely you should be able to use a modern browser/node that understands most of the code as is.

Even with transpiler, most of them generate source maps that make debugging transparent. The big problems are transpilers that change the order of execution or break sourcemaps. Babel plugin for async/await was one of those. With proper setup, debugging async/await and generator functions is pretty simple again.