DEV Community

Like `console.log` But Better

Leira Sánchez on February 26, 2020

Who hasn't peppered their code with console.logs in an attempt to find that pesky bug? The logs can get daunting and confusing. These will help you...
Collapse
 
tylerlwsmith profile image
Tyler Smith

Great article, I had never heard on console.assert!

One of the things that I starting doing as a short hand for writing labels is wrapping the variables in an object literal. It saves on the repetitive typing!

const firstName = 'Leira';
const lastName = 'Sánchez';
console.log({firstName, lastName}); // {firstName: "Leira", lastName: "Sánchez"}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leirasanchez profile image
Leira Sánchez

Wow! This great! I will definitely be using this from now on. Thank you 🙂

Collapse
 
vbelolapotkov profile image
Vasily Belolapotkov

I like that trick too! And now with console.table you can make it look even better!

Collapse
 
ben profile image
Ben Halpern

I like these things because they're just about as simple as console.log but more useful in a lot of cases.

I have a hard time adopting debugging tools any more complicated than print statements.

Great post!

Collapse
 
cathyc93 profile image
Cathy Casey-Richards

Totally agree! Very simple tips that can be used right away.

Collapse
 
daveblythe profile image
Dave Blythe (he/him)

Thanks, Ben.... so much feels here!
It feels so good when someone else acknowledges things like this, really:

"I have a hard time adopting debugging tools any more complicated than print statements"

This 'validates' for those of us who still fumble around semi-blindly with the classic duo of console.log() and alert(stuff) :D

Collapse
 
dionnyprensa profile image
Dionny Prensa

It is also possible to use console.log with JSON.stringify (some Object, null, 2)
Example

Collapse
 
bernardbaker profile image
Bernard Baker

A good use case for JSON.stringify is that in some cases console.log does not print the true value of its arguments.

So wrapping the argument in JSON.stringify prints the actual value.

Collapse
 
spiralx profile image
James Skinner

It does print the true value, if you log a variable and then reassign it later the console log will show the original value. However properties of that variable may have changed since the log statement was made and the console only evaluates properties when you expand an object in the console, so you get the current values instead of those at the time you called console.log.

If you're interested in shallow properties you can just log { ...obj } instead of obj, or if you want the entire tree of properties you can use something like Lodash's cloneDeep to get a copy of the object and all nested properties.

npmjs.com/package/lodash.clonedeep

Thread Thread
 
bernardbaker profile image
Bernard Baker

Could you run this code in a web debugger?

var myVar = {a: true};
var myVar2 = {};
myVar2.b = myVar; // {b: {a: true})
myVar.a = false;
console.log(myVar2); // === {b: {a:false}}

What output do you get?

Thread Thread
 
spiralx profile image
James Skinner

{b: {a:false}}, which is as expected.

Thread Thread
 
bernardbaker profile image
Bernard Baker

Must have been the wrong example.

Collapse
 
jamesthomson profile image
James Thomson

Don't forget about console.dir! 🙂

Collapse
 
navin_moorthy profile image
Navin

I often use console.dir to see the DOM attributes of an element

Collapse
 
devtronic profile image
Julian Finkler
let firstName = "John";
let lastName = "Doe";
console.log('First Name: %s, Last Name: %s', firstName, lastName);
// First Name: John, Last Name: Doe
Collapse
 
easilybaffled profile image
Danny Michaelis

Great post, Leira! I love seeing more people use styles in their logging. I'd like to add one more to your list, console.tap. It's one of my own creation, made to solve the fact that console.log returns undefined. Instead tap returns the first value you passed in. Imagine trying to log the result of the filter:

['1', '2', 'zero' , 3, 4, 5]
    .map(parseNumbers)
    .filter(removeEvens)
    .reduce(( acc, v ) => Math.max(acc, v))
Collapse
 
bashunaimiroy profile image
Bashu Naimi-Roy

This is fascinating and addresses a frequently encountered awkwardness of console.log, thank you! I'm going to start using this a lot

Collapse
 
leirasanchez profile image
Leira Sánchez

I will definitely check it out. Thank you!

Collapse
 
metruzanca profile image
Samuele Zanca

You forgot the most important console method:

console.group("group name");
console.log("something");
console.groupEnd();

Which creates a collapsible tree for hiding and showing more or less information.

Also console.time and console.timeEnd to track how long something took.

Collapse
 
leirasanchez profile image
Leira Sánchez

I’m going to have to start using groups. They will definitely make my console cleaner! Thank you

Collapse
 
kosovych profile image
Yaroslav Kosovych

Dont forget about console.time() and console.timeEnd() for performance tracking. console.trace to log track trace and many others cool features :)

Collapse
 
markohologram profile image
Marko A

console.trace was just the one I wanted to mention. Whenever I jut want to trace call stack to just see the flow of function calls better.

Collapse
 
jerp86 profile image
José Eduardo Rodrigues Pinto

CSS in console.log

console.log('%cHello World!', 'font-weight: bold; font-size: 50px; color: red; text-shadow: 3px 3px 0 rgb(217,31,38), 6px 6px 0 rgb(226, 91,14), 9px 9px 0 rgb(245,221,8), 12px 12px 0 rgb(5,148,68), 15px 15px 0 rgb(2,135,206), 18px 18px 0 rgb(4,77,145), 21px 21px 0 rgb(42,21,113)');('%cHello World!', 'font-weight: bold; font-size: 50px; color: red; text-shadow: 3px 3px 0 rgb(217,31,38), 6px 6px 0 rgb(226, 91,14), 9px 9px 0 rgb(245,221,8), 12px 12px 0 rgb(5,148,68), 15px 15px 0 rgb(2,135,206), 18px 18px 0 rgb(4,77,145), 21px 21px 0 rgb(42,21,113)');

Collapse
 
pavanmehta profile image
Pavan Maheshwari

Console.group and console.groupEnd is also very useful.

Collapse
 
spiralx profile image
James Skinner • Edited

You can use more than one %c in a console string, and use '' to reset styles e.g.

console.log('%cvalue%c = %s', 'font-weight: bold; color: red;', '', str)

If you want some very fancy output you can use this package, which supports multi-line styled output including inline objects and HTML elements:

github.com/astoilkov/console.message

You can even use the CSS trick to display images in the console!

github.com/adriancooney/console.image

Collapse
 
fergarram profile image
Fernando Garcia

I had no idea, now I won’t forget! Thanks for sharing!

Collapse
 
yerac profile image
Rich • Edited

Just be aware of support though. We found that console.dir for example wasn't supported by a couple of browsers a year or so back and had to write polyfills! Only an issue if you are baking them into the app (i.e. error handling methods) rather than debugging in devtools

Oddly console.dir is supposedly widely supported even in ie9, but we found this wasn't always the case...

Collapse
 
navin_moorthy profile image
Navin

Checkout the Colored Console log extension for VSCode.

marketplace.visualstudio.com/items...

You can have Flair on all console.log with just a keypress. Also, you can change the styling directly in the extension.

Collapse
 
leirasanchez profile image
Leira Sánchez

This seems promising. I will try it. Thank you

Collapse
 
jeastham1993 profile image
James Eastham

Had no idea this was possible, great post Leira

Collapse
 
thatzacdavis profile image
Zachary Davis

The CSS one was new to me haha, I see some nice troll error messages for my teammates coming in the future

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

I like the console.table() as every now and then we deal with json response. This could come handy as it is readable.

Collapse
 
hamzahamidi profile image
Hamza Hamidi

I prefer using the debugger over the console.log. This way I can control the steps I want to see from the debugger & most importantly I can see the call stack.

Collapse
 
sansseryph profile image
Kyla

All of this information is blowing my mind, especially the fact that you can style console outputs!

Collapse
 
leirasanchez profile image
Leira Sánchez

I’m glad you find it useful!

Collapse
 
trungmnguyen profile image
Trung Nguyen

Good work. Very helpful and informative.

Collapse
 
jprando profile image
Jeudi Prando

congratulations for sharing Leira

Collapse
 
sinteticwizard profile image
Ramon Ramirez

console log with css, i like that

Collapse
 
gsonderby profile image
Gert Sønderby

Console.table is one I wasn't aware of before. I'll definitely use that one.

Collapse
 
laurence profile image
laurence

Thanks for posting will help me with my exploring, debugging and testing quickly whilst learning new JavaScript concepts etc.

Collapse
 
mahdiafzal profile image
Mahdi Afzalalghom

Thankful
The article was very interesting

Collapse
 
l_giraudel profile image
Loïc Giraudel

I now prefer log points in Chrome Dev Tools. It was already possible before with conditional break points but not as easy as the log points :)

Collapse
 
leirasanchez profile image
Leira Sánchez

I have never tried log points. I will look into them. Thank you

Collapse
 
codeposse profile image
CodePosse

I love nerdy console statements

Collapse
 
darion1 profile image
DarioN1

Thanks, till now I only userd console.log, now I'm going deep with console.table ;-)

Collapse
 
abdelrahmanahmed profile image
Wahdan

Long live “console.log”

Collapse
 
cathyc93 profile image
Cathy Casey-Richards

These are great tips! Thanks for sharing 😄

Collapse
 
c00lhawk607 profile image
c00lhawk607

Is there a css for python's log/command terminal?

Collapse
 
leirasanchez profile image
Leira Sánchez

I haven't learned Python yet so I can't help you. Hopefully another reader is able to answer this question!

Collapse
 
sergiointoronto profile image
Sergio

Great post! I didn't know about most of these. Very helpful!

Collapse
 
vishalpaalakurthi profile image
vishalpaalakurthi

Article is very helpful.

console.error also useful for debugging.

Collapse
 
berns_churches profile image
Berns Fire Death

This is a game-changer. I have never actually thought of looking up the console documentation until I read your article. This is very cool.

Collapse
 
sargis profile image
Sargis

Don't forget about console.time

Collapse
 
leirasanchez profile image
Leira Sánchez

Great when pairing it with console.timeEnd() !

Collapse
 
jerinoommen profile image
Jerin Oommen

Never knew about console.table, thank you!!!

Collapse
 
mageakos profile image
george simantiras

Console.time(label) and console.timeEnd(label)
Are useful to count how long an operation has taken, for performance tuning