TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Use console.log() like a pro (2020)

700 pointsby vuciv1about 4 years ago

47 comments

jchwabout 4 years ago
Another trick that might be more practical for actually debugging is using the object shorthand. For example, instead of...<p><pre><code> console.log(x, y); </code></pre> which contains the information you need, but lacks any useful context, try...<p><pre><code> console.log({x, y}); </code></pre> ...which will print out like an object, including the key names.
评论 #26785217 未加载
评论 #26780648 未加载
评论 #26781813 未加载
评论 #26780933 未加载
评论 #26781025 未加载
评论 #26780651 未加载
评论 #26780791 未加载
umaarabout 4 years ago
I&#x27;ve put over 200 tips like that on my website: <a href="https:&#x2F;&#x2F;umaar.com&#x2F;dev-tips&#x2F;" rel="nofollow">https:&#x2F;&#x2F;umaar.com&#x2F;dev-tips&#x2F;</a><p>Each tip has a textual explanation, and an animated gif if you&#x27;re a visual learner (I know, I need to scrap gifs and move to regular videos).<p>There&#x27;s a lot of tricks there which can hopefully improve your development and debugging workflows. Let me know if there are specific things you&#x27;d like to see. A few people have asked for how to find memory leaks.
评论 #26783844 未加载
评论 #26781137 未加载
评论 #26789028 未加载
评论 #26781035 未加载
pjungwirabout 4 years ago
Wow there are some cool tricks here!<p>In Firefox any objects you pass to console.log are expandable, so you can say console.log(&quot;my hash&quot;, h). It seems to behave the same when you say console.log(&quot;my hash %o&quot;, h).<p>But there is a tricky thing that has really confused me in some debugging efforts: when expanded, the object display is &quot;live&quot;, so it always shows the <i>current</i> 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:<p><pre><code> h = {foo: &quot;bar&quot;} console.log(h) ▶ Object { foo: &quot;bar&quot; } h.foo = &quot;BAR&quot; </code></pre> Then you click the triangle and you see:<p><pre><code> ▼ {..} | foo: &quot;BAR&quot; | ▶ &lt;prototype&gt;: Object { .. } </code></pre> I don&#x27;t know if that&#x27;s a bug or desired behavior, but watch out for it! In the past I&#x27;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.
评论 #26780883 未加载
评论 #26781157 未加载
ajcpabout 4 years ago
My whole personal site[1] is one big console.log(), right down to theme matching :D Unfortunately I&#x27;m not sure anyone has actually noticed.<p>1: <a href="https:&#x2F;&#x2F;itsokayitsofficial.io&#x2F;" rel="nofollow">https:&#x2F;&#x2F;itsokayitsofficial.io&#x2F;</a>
评论 #26781219 未加载
评论 #26781042 未加载
评论 #26782591 未加载
评论 #26782497 未加载
onion2kabout 4 years ago
If you&#x27;re using console.log to do debugging then it&#x27;s worthwhile giving yourself a little more data to point at where a problem might lie - timings.<p>Open up devtools (cmd+option+j), then open the command palette (cmd+shift+P), and then search for &quot;console&quot;, and then select &quot;Console - Show Timestamps&quot;. Now every console output will have the high definition timestamp prepended to it. That can be really helpful if you don&#x27;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.<p>(This probably only works in Chrome)
评论 #26781104 未加载
mdanielabout 4 years ago
All that text and no links to the reference docs to allow one to learn to fish and also learn about changes in the future: <a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;API&#x2F;Console" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Web&#x2F;API&#x2F;Console</a>
aerovistaeabout 4 years ago
Let me save someone a few minutes of confusion: generally I use console.table instead of console.dir ever since I discovered console.dir is basically unpredictable. Try using it on an Error or anything that inherits from Error and you&#x27;ll see it puts out what looks like an expandable stack trace. I have no idea how or why it&#x27;s implemented to do that, but basically it just varies from one object to the next and I dislike that.
评论 #26781455 未加载
eyelidlessnessabout 4 years ago
Since I don’t see it mentioned yet: my favorite thing to do if I’m console slumming is to use it as a comma-separated expression. You can use console.log(), foo as a single expression (eg as an arrow function return) the log is executed but its undefined return value discarded. This saves a lot of keystrokes where you’d otherwise have to wrap the function body in braces with an explicit return statement.
Kaze404about 4 years ago
My (newly discovered) favorite trick is using the comma operator. Using it, you can (admittedly horribly) log anything in the middle of any expression.<p>This for example will call `console.log(myVar)` and still call `someFunction(myVar, someOtherArgument)`.<p><pre><code> myVar = &quot;12345&quot; someFunction((console.log(myVar), myVar), someOtherArgument); </code></pre> Pretty handy sometimes :)
brundolfabout 4 years ago
Another little trick; instead of doing:<p><pre><code> console.log(&quot;some label: &quot; + JSON.stringify(someObj)) </code></pre> pass it as a separate parameter:<p><pre><code> console.log(&quot;some label: &quot;, someObj) </code></pre> and you&#x27;ll get interactive expansions&#x2F;manipulation in the console
评论 #26781421 未加载
SavantIdiotabout 4 years ago
Not gonna lie, read this hoping to pat myself on the back for being a pro, twist: learned some cool stuff, console.memory()? Neato!
评论 #26780624 未加载
评论 #26780977 未加载
评论 #26780961 未加载
christiansakaiabout 4 years ago
I often always do this to deep print my javascript object. console.log(JSON.stringify(myObject, null, 4));
评论 #26780499 未加载
Timothycquinnabout 4 years ago
One missing mention is `console.groupCollapsed(label)` which is handy for nesting large dumps of data that you don&#x27;t want to steal visual real estate.<p>Eg: console.groupCollapsed(&#x27;data$ at load&#x27;); console.groupCollapsed(&#x27;GridData&#x27;); console.table(data$.GridData.toList()); console.groupEnd(); console.groupCollapsed(&#x27;Loads&#x27;); console.table(data$.Loads.toList()); console.groupEnd(); console.groupCollapsed(&#x27;Drv&#x27;); console.table(data$.Drv.toList()); console.groupEnd(); console.groupEnd();<p>This will present `&gt; 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.
yepthatsrealityabout 4 years ago
&gt; Using console.log() for JavaScript debugging is the most common practice among developers. But, there is more…<p>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.<p>You should use a debugger in every language you can for development.<p>Neat tricks though.
评论 #26784875 未加载
评论 #26786498 未加载
评论 #26794695 未加载
turdnagelabout 4 years ago
Console.group is one of my favorite features but Chrome does not handle filtering it very well. Basically, if you want to filter on a certain term, all the groups will remain, even if nothing from those groups (title, subfields, otherwise) matches. There has been a Chromium bug open since 2014: <a href="https:&#x2F;&#x2F;bugs.chromium.org&#x2F;p&#x2F;chromium&#x2F;issues&#x2F;detail?id=363796" rel="nofollow">https:&#x2F;&#x2F;bugs.chromium.org&#x2F;p&#x2F;chromium&#x2F;issues&#x2F;detail?id=363796</a>
评论 #26784927 未加载
tfshabout 4 years ago
I use the console.dir method occasionally to get the public methods and properties of HTML elements, for instance console.dir(document.body) would output all the methods and properties
ehsankiaabout 4 years ago
Sometimes you wanna see the value of a variable but it&#x27;s inside a hot function and ends up spamming&#x2F;freezing your console if you log it.<p>Not quite a console.log statement, but Live Expression in DevTools is pretty useful for that. It&#x27;s the little &quot;eye&quot; next to filter at the top, and it&#x27;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.
uytabout 4 years ago
console.log can also be styled! It&#x27;s a restricted subset of css so you have to hack around it, but it&#x27;s good enough to make images display:<p><pre><code> img = $$(&#x27;img&#x27;)[0]; &#x2F;&#x2F; console.log(img); console.log(&quot;%cPlaceholder&quot;, `background:url(&quot;${img.src}&quot;) no-repeat cyan; border:1px solid black; padding:${img.naturalHeight}px ${img.naturalWidth}px 0 0; font-size:0; line-height:0;`); </code></pre> If you paste this you should see the HN logo display in your console. Credit for the image trick goes to <a href="https:&#x2F;&#x2F;github.com&#x2F;adriancooney&#x2F;console.image" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;adriancooney&#x2F;console.image</a><p>I 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.
I_am_tiberiusabout 4 years ago
Very important for backend is %j (e.g.: console.log(&#x27;%j&#x27;, variable); which can output complex json objects to the terminal. I often write it to the terminal and then copy it to an online json viewer so it is formatted in a viewable format.
评论 #26784020 未加载
评论 #26784503 未加载
alkonautabout 4 years ago
Is there any way to add logging that is stripped at build time? Like in C# if I have a “Debug.WriteLine” it doesn’t exist if built in release mode. I now build ts to js with a “dev” config, could that not strip out all console.debug for me?
swyxabout 4 years ago
for what its worth i have this guy blocked on twitter - all he does is repost basic APIs you can get from MDN. classic grift playbook.
评论 #26784049 未加载
supermattabout 4 years ago
This brings to light an issue I have encountered recently which has caused me to rely on console.log more than I would like.<p>In a recent project I have started using async&#x2F;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&#x2F;await if I cant fix this issue.<p>Has anyone experienced this? If so, is there a way to fix it, or is this what I can expect when using async&#x2F;await?
评论 #26782959 未加载
techbubbleabout 4 years ago
You can get the same behavior as console.log() without cluttering up your code by using LogPoints.<p><a href="https:&#x2F;&#x2F;developer.chrome.com&#x2F;blog&#x2F;new-in-devtools-73&#x2F;" rel="nofollow">https:&#x2F;&#x2F;developer.chrome.com&#x2F;blog&#x2F;new-in-devtools-73&#x2F;</a><p><a href="https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Tools&#x2F;Debugger&#x2F;Set_a_logpoint" rel="nofollow">https:&#x2F;&#x2F;developer.mozilla.org&#x2F;en-US&#x2F;docs&#x2F;Tools&#x2F;Debugger&#x2F;Set_...</a>
Pfhreakabout 4 years ago
Rather than using<p><pre><code> %s, %i, %o, %f, etc. </code></pre> You can use a templated string, like this:<p><pre><code> `This is a string that has been printed ${someVar} times.`</code></pre>
评论 #26781121 未加载
faichaiabout 4 years ago
Was reading this thinking the biggest pain is being unable to wrap console.log and keep line numbers.<p>But some Googling [1] shows that this has now been fixed by being able to blackbox your wrapper scripts.<p>[1] <a href="https:&#x2F;&#x2F;gist.github.com&#x2F;paulirish&#x2F;c307a5a585ddbcc17242" rel="nofollow">https:&#x2F;&#x2F;gist.github.com&#x2F;paulirish&#x2F;c307a5a585ddbcc17242</a>
boredpandas777about 4 years ago
I didn&#x27;t know about .memory, .trace() and .assert(), all of which are very helpful. Up till now, I&#x27;ve had to add a try-throw-catch to get a stack trace and be able to follow synchronous execution flow leading up to a given function call, but console.trace will do that for me, so yay.
virgil_disgr4ceabout 4 years ago
I used to think `console.log` was only good for soothing and assuaging the limbs of trees. Now I know better!
评论 #26781080 未加载
chensterabout 4 years ago
Would be nice to also include console.table() explained on <a href="https:&#x2F;&#x2F;phpcontrols.com&#x2F;blog&#x2F;debugging-javascript-go-beyond-console-log" rel="nofollow">https:&#x2F;&#x2F;phpcontrols.com&#x2F;blog&#x2F;debugging-javascript-go-beyond-...</a>
deckard1about 4 years ago
If I&#x27;m looking at values in node, I typically do<p><pre><code> console.dir(obj, { depth: null }) </code></pre> However, if you need to inspect some object in a browser, don&#x27;t forget you can just insert:<p><pre><code> debugger </code></pre> Which can be helpful at times.
laurent123456about 4 years ago
Please don&#x27;t add colours to your console.log statements. It might look nice in the Chrome console, but as soon as your messages end up elsewhere, in a terminal or text file for instance, it makes the statements look very messy.
评论 #26784794 未加载
shp0ngleabout 4 years ago
Another tip I found very useful lately<p>You can use `$(&quot;selector&quot;)`, even without jQuery, in console. (not sure if with firefox, works with safari and chrome)<p>And also `$x(&quot;path&quot;)` for xpath.<p>But note, this works only in console, it’s not available from javascript.
评论 #26781206 未加载
评论 #26783030 未加载
评论 #26781190 未加载
nicetryguyabout 4 years ago
Nice little article. Learned a new trick or two.<p>I&#x27;d love to see one on the step-thru debugger!
lights0123about 4 years ago
<p><pre><code> %s – string %i or %d – integer %o or %O – object %f – float </code></pre> Why were these ever specific types, instead of just one option that looks at the parameter type?
评论 #26784130 未加载
评论 #26780737 未加载
评论 #26780672 未加载
rattrayabout 4 years ago
The ones that were new and interesting to me were towards the end:<p><pre><code> console.table(obj) console.time(&#x27;x&#x27;); console.timeEnd(&#x27;x&#x27;) console.trace()</code></pre>
jackconsidineabout 4 years ago
Didn&#x27;t know about the string interpolation. Don&#x27;t see a reason to use that over built in JS string interpolation (i.e. `var is ${var]`), but still interesting.
评论 #26783133 未加载
yakshaving_jgtabout 4 years ago
There&#x27;s pro, and then there&#x27;s Steven Wittens. Open the console on his site.<p><a href="http:&#x2F;&#x2F;acko.net&#x2F;" rel="nofollow">http:&#x2F;&#x2F;acko.net&#x2F;</a>
kache_about 4 years ago
I keep on coming back to debugging with print statements. I (embarrassingly) started using console.trace more often only recently.
drhayes9about 4 years ago
If you select an item with the inspector (Chrome or Firefox), you can now refer to that HTML element as $0 in the console.
hartrorabout 4 years ago
console.clear() is the worst. I&#x27;ve had to fight rogue calls to capture debugging information.
darepublicabout 4 years ago
Never knew about console.memory, that will be help the next time I feel paranoia about mem leaks!
kebmanabout 4 years ago
Hey, this is pretty neat! Never knew you could assert with it also. This&#x27;ll come in handy!
keitrealabout 4 years ago
I do `window.c = console`, and there is no looking back. It can save a lot of key strokes
paweladamczukabout 4 years ago
I think the very fact that you have to rely on things like that when debugging speaks volumes about the language deficiencies. Or maybe it&#x27;s just the tooling or environments where JS is executed?<p>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.
评论 #26783444 未加载
评论 #26783970 未加载
baybal2about 4 years ago
console.table O_O<p>Wow, since when it was in JS?
评论 #26780958 未加载
kkevvabout 4 years ago
Amazing, console.dir definitely beats console.log(JSON.stringify(...))
intellixabout 4 years ago
99% of Frontend developers don&#x27;t know about the debugger&#x2F;developer tools. You can even log stuff without ever writing&#x2F;compiling directly from Chrome Developer Tools
评论 #26785391 未加载
评论 #26787674 未加载
keyleabout 4 years ago
OK. I would argue that if you spend that much time making your console look pretty (beyond useful), then you&#x27;re either not spending enough time on things that matter (everything else, that the user may see) or you&#x27;re grossly over budgeted.<p>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.