700 points · by vuciv1 · 5y ago · 148 comments
console.log(x, y);
which contains the information you need, but lacks any useful context, try... console.log({x, y});
...which will print out like an object, including the key names.In a local build you basically have a 1:1 mapping of source code to deployed code and the debugger here basically becomes your IDE. You can hit Ctrl+Shift+P in the inspector and use the same kind of fuzzy file matcher you have in Sublime Text or VS Code, and from there you can set breakpoints, modify the code in memory, and so on. The console will reflect on the entire scope and annotate the code with their runtime values, the same as you get when working inside a JetBrains IDE.
But it's JS, so you can tweak it without committing it to disk and so you get some form of REPL driven development. I can't remember the last time I've used a console.log over setting a breakpoint in the debugger and fucking with the application state at that point to understand an issue.
You can get quite close to that after you've bundled your code and deployed it to a server, so long as you've got good source maps going on.
Print debugging is invaluable, but I can't help but think there's something of Smalltalk or Lisp in how you can mess with your app within a sandbox through the inspector, at runtime. The only thing that breaks the model is the transpilation and minification, without sourcemaps.
Then you quit web development and start a new career.
Doesn't help on browser, though; the options arg to console.dir isn't part of the standard there.
Try this in a browser console: x={a:1,b:{c:1}};console.log(x);x.b.c=2;
then 'expand' the object, 'c' will be logged as 2, not 1
Each tip has a textual explanation, and an animated gif if you're a visual learner (I know, I need to scrap gifs and move to regular videos).
There's a lot of tricks there which can hopefully improve your development and debugging workflows. Let me know if there are specific things you'd like to see. A few people have asked for how to find memory leaks.
In Firefox any objects you pass to console.log are expandable, so you can say console.log("my hash", h). It seems to behave the same when you say console.log("my hash %o", h).
But there is a tricky thing that has really confused me in some debugging efforts: when expanded, the object display is "live", so it always shows the current properties of the object, not the properties as they were when you printed them. But the unexpanded view shows them as they were. So for example:
h = {foo: "bar"}
console.log(h)
▶ Object { foo: "bar" }
h.foo = "BAR"
Then you click the triangle and you see: ▼ {..}
| foo: "BAR"
| ▶ <prototype>: Object { .. }
I don't know if that's a bug or desired behavior, but watch out for it! In the past I've used console.log(JSON.stringify(h)) to capture the full object as-is. I guess turning it back into an object would be even nicer, so you could have a deep copy to navigate.I've posted about it in more detail here: https://news.ycombinator.com/item?id=26785429.
I think it would be more confusing if the console did not work like the rest of the language does.
That is entirely irrelevant. The primary purpose of `console.log` is and has always be to generate output from normal, non-interactive programs.
And it's completely wrong, `console.log` was absolutely intended as a logging method, as evidenced by its siblings `debug`, `info`, `warn` and `error`, pretty much like every logging API out there.
It's also ahistorical revisionism "the console" was added very late into the history of the language, it and the entire console API were added by Firebug in the mid aughts. The language had been a thing for a decade at that point.
> I think it would be more confusing if the console did not work like the rest of the language does.
It would be the exact opposite. When I try to output something, my intent is to show the state of that thing at that point. That JS consoles are lazy (and even deferred) has systematically been a pain point and a pain in the ass leading to eager deep cloning to ensure I can see what I actually have on hand at that point, especially in mutation-heavy code.
I'm absolutely certain the number of times I've considered the behaviour a feature rather than an annoyance is 0.
There's a more in-depth answer SO: https://stackoverflow.com/a/23392650
But you should proofread it for typos.
Open up devtools (cmd+option+j), then open the command palette (cmd+shift+P), and then search for "console", and then select "Console - Show Timestamps". Now every console output will have the high definition timestamp prepended to it. That can be really helpful if you don't want to go down the whole perf chart rabbit hole, or if you think things might be running in the wrong order due to some async weirdness.
(This probably only works in Chrome)
Though you probably want the per-tab Console there (ctrl-shift-k). ctrl-shift-j would give you the multiprocess browser console, which is very noisy.
This for example will call `console.log(myVar)` and still call `someFunction(myVar, someOtherArgument)`.
myVar = "12345"
someFunction((console.log(myVar), myVar), someOtherArgument);
Pretty handy sometimes :) console.log("some label: " + JSON.stringify(someObj))
pass it as a separate parameter: console.log("some label: ", someObj)
and you'll get interactive expansions/manipulation in the console console.log("some label: " + JSON.parse(JSON.stringify(someObj)))Technically you'd have to do
console.log("some label: ", JSON.parse(JSON.stringify(someObj)))
> In the second version, if someObj changes after it was logged, when you'll expand it you'll see the updated valueYes, this is something to be aware of (and is getting beaten to death throughout this comments section), but if like me you mostly use plain objects in an immutable way, you generally don't have to bother with cloning. Just keep this in the back of your head and know when it won't do what you want in a particular context.
I would never debug with that mindstate. I don't trust myself.
By printing out the object you get a point-in-time snapshot rather than a reference to a mutable object.
Eg: console.groupCollapsed('data$ at load'); console.groupCollapsed('GridData'); console.table(data$.GridData.toList()); console.groupEnd(); console.groupCollapsed('Loads'); console.table(data$.Loads.toList()); console.groupEnd(); console.groupCollapsed('Drv'); console.table(data$.Drv.toList()); console.groupEnd(); console.groupEnd();
This will present `> data$ at load` and clicking on the chevron will open the data showing the list of entries and clicking on their chevrons will show the table for each.
Cut your debugging time, knowledge of console.log, and mental churn in half and set up your tooling to use a `debugger` statement. The console.log method may be used heavily but it’s actually a bad practice and often leaves code littered with log statements. Even for the purpose of logging itself you should use a logging library for serious development.
You should use a debugger in every language you can for development.
Neat tricks though.
1. You can see where you are at that moment of execution in code
2. You can see variables and arguments within scope
3. You can forget about it and a linter will pick it up or it will be ignored unless run in debugging mode
All of this allows you to focus on the actual bug and not looking for something like:
`MY SPECIAL VAR: [object Object]`
I forgot to format, let's run it again.
I find interactive debugging takes more concentration than a workflow of: form hypothesis, add the console.logs to prove/disprove it, run the code, and analyze the result.
Not quite a console.log statement, but Live Expression in DevTools is pretty useful for that. It's the little "eye" next to filter at the top, and it'll constantly watch an expression and show the latest value. Worst case you can assign your value to `window.myValue` and put a watch on that.
img = $$('img')[0];
// console.log(img);
console.log("%cPlaceholder", `background:url("${img.src}") no-repeat cyan; border:1px solid black; padding:${img.naturalHeight}px ${img.naturalWidth}px 0 0; font-size:0; line-height:0;`);
If you paste this you should see the HN logo display in your console. Credit for the image trick goes to https://github.com/adriancooney/console.imageI use this a lot for working with animated canvases. Appending the current frame into the page is not the same since you lose the context you get from being interleaved with your other log messages.
Maybe you can skip a step with pasting online.
I don't think closing on people just starting to learn is a good way to expand the field of software engineering.
In a recent project I have started using async/await, and seem to have lost the ability to use the debugger effectively. Breakpoints no longer seem to work properly. Its a huge negative, and im thinking of rewriting a lot of the code to remove async/await if I cant fix this issue.
Has anyone experienced this? If so, is there a way to fix it, or is this what I can expect when using async/await?
https://developer.chrome.com/blog/new-in-devtools-73/
https://developer.mozilla.org/en-US/docs/Tools/Debugger/Set_...
%s, %i, %o, %f, etc.
You can use a templated string, like this: `This is a string that has been printed ${someVar} times.`But some Googling [1] shows that this has now been fixed by being able to blackbox your wrapper scripts.
console.dir(obj, { depth: null })
However, if you need to inspect some object in a browser, don't forget you can just insert: debugger
Which can be helpful at times.You can use `$("selector")`, even without jQuery, in console. (not sure if with firefox, works with safari and chrome)
And also `$x("path")` for xpath.
But note, this works only in console, it’s not available from javascript.
I'd love to see one on the step-thru debugger!
%s – string
%i or %d – integer
%o or %O – object
%f – float
Why were these ever specific types, instead of just one option that looks at the parameter type?laughs in JS
console.table(obj)
console.time('x'); console.timeEnd('x')
console.trace()In any case, the debugging experience is probably the biggest reason why I dislike modern web dev and tend to steer my career towards back-end.
I use the browser debuggers as well but I never saw a JS stack trace approaching readability of a C# stack trace, and there are also other things that make the entire debugging experience more troublesome. Maybe that's just because I have very little front-end experience (and no workflows and IDEs properly set up to work with particular frameworks). Or maybe it's because of the JS ecosystem. Threads like this one make me lean towards the latter.
I also can’t stress enough how nice it is to have the debugger integrated into the runtime environment as opposed to an auxiliary debugger like GDB. No need to launch the debugger after my code breaks because it’s already there.
I think web technology has come a long way in the past few years, but a lot of people still seem to hold a grudge against it that I can only imagine they developed in the days of “jQuery all the things”. Are there still problems? Massively yes, but what ecosystem is perfect? I think if you don’t have much recent experience, it can’t hurt to try these things again with an open mind and see if your opinions still hold. I personally don’t have any experience with C# to be able to compare the debugging experience, but compared to Go or C/C++ I think it is massively better.
I think with a good setup including a LSP server for your editor, a good linter, and a type checker, frontend development is actually one of the more enjoyable ways to write code.
Tangential, but the only feature I really miss from browser debuggers is time travel debugging. Mozilla was working on implementing this in the Firefox DevTools as “WebReplay” [0] but it was spun out as a separate project called Replay.io [1] and I haven’t heard much about it since then.
[0]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/We...
A language/runtime/framework gives you options and you pick your poison, browsers offer you step by step debuggers and REPL out of the box and I actually think it's awesome in terms of debugging, you can of course only use console.log(), and it's a good place to start. When you're ready to move on there are many more useful tabs in the browser devtools to debug with.
I have yet to see a mid-level engineer using the same method when debugging C# code.
Despite all that, I try to refrain from strong statements about technologies. Just throwing around ideas.
Wow, since when it was in JS?
https://developer.mozilla.org/en-US/docs/Web/API/Console/tab...
How is that possible?
> Most frontend developers in my experience don't know about developer tools.
I still don't know how that's possible though.
Btw none of this is as useful as a breakpoint. Type `debugger;` in your code, refresh chromium or what have you with the dev panel open and inspect everything, jump over etc. ad nauseam. Pro tips use IntelliJ or webstorm for a really nice experience debugging.