DEV Community

Cover image for Neat console tricks to try out
Karin
Karin

Posted on • Originally published at khendrikse.netlify.app on

Neat console tricks to try out

Cover image by Stephan Seeber on Unsplash

A big chunk of working as a JavaScript developer is debugging your (or someone elses) code. Often I see people using the trusty console.log('Data: ', data) to get some insights on the inner happenings of their data variable. And I usually respond with an excited: "Can I show you a neat trick?" I'll do the same in this piece: let me show you a few neat tricks that'll make debugging much, much easier.

Let's start simple: finding your console message

Consoles tend to run wild with different messages. This can make it hard to see your console message. For example:

onoes: a random warning message, you might want to read all of this but you probably won't.
Please see the documentation at blabla.com if you want to know more.
onoes: a random warning message, you might want to read all of this but you probably won't.
Please see the documentation at blabla.com if you want to know more.
My log message
onoes: a random warning message, you might want to read all of this but you probably won't.
Please see the documentation at blabla.com if you want to know more.
Enter fullscreen mode Exit fullscreen mode

People tend to solve this by doing something like

const message = 'My log message';
console.log('message: ', message);

// message: My log message
Enter fullscreen mode Exit fullscreen mode

Especially when logging variables of which you don't know the value, this can be a useful way to find the message between all your other logs. But there is a quicker way:

const message = 'My log message';
console.log({ message });

// {message: 'My log message'}
Enter fullscreen mode Exit fullscreen mode

Adding the curly brackets turns your log into an object, thus showing up as one.
Honestly, this is the main trick I wanted to share. But just for fun, here are a few extra's:

Asserting with console.assert()

If you want to know if something is true or false you could do something like:

const awesome = true;
const notFun = false;

console.log('Is similar?', awesome === notFun);
// Is similar? false
Enter fullscreen mode Exit fullscreen mode

But with console.assert() you can pass the condition to check, and a message to throw if the condition asserts as false:

const awesome = true;
const notFun = false;

console.assert(awesome === notFun, 'not similar');
// Assertion failed: not similar
Enter fullscreen mode Exit fullscreen mode

Is it that different? Not really, but the nice thing is that the log will be shown as an error message, making it easier to find when it asserts to false.

Inspecting objects with console.dir

When using console.log() to log an object, the output will be a toString representation of the object. It differs where you do this though.
Some browsers will also show a tree with the object properties, but others might not.

Using console.dir() to log an object will output an interactive list of the object's properties.

const anObject = { foo: 'foo', bar: 'bar', greetings: ['hello', 'hi', 'sup'] };

console.log(anObject);
// {foo: 'foo', bar: 'bar', greetings: Array(3)}

console.dir(anObject);
// Object
//   bar: "bar"
//   foo: "foo"
//   greetings: (3) ['hello', 'hi', 'sup']
//   [[Prototype]]: Object
Enter fullscreen mode Exit fullscreen mode

Checking a bunch of data with console.table

If you want to inspect a big array or object, using console.data() might be a nice way to get a quick overview of what is inside your variable.
When using this functionality, the console will log out your data in the form of a table using the first column as an index.
If you're logging an array, the indexes will be the index of each array entry. If you're logging an object, the key will be the index for each row.

Do note that there is a limit of a 1000 rows!

const anObject = { foo: 'foo', bar: 'bar', greetings: ['hello', 'hi', 'sup'] };

console.log(anObject);
// {foo: 'foo', bar: 'bar', greetings: Array(3)}

console.table(anObject);
// ┌───────────┬─────────┬──────┬───────┬────────┐
// │  (index)  │    0    │  1   │   2   │ Values │
// ├───────────┼─────────┼──────┼───────┼────────┤
// │    foo    │         │      │       │ 'foo'  │
// │    bar    │         │      │       │ 'bar'  │
// │ greetings │ 'hello' │ 'hi' │ 'sup' │        │
// └───────────┴─────────┴──────┴───────┴────────┘
Enter fullscreen mode Exit fullscreen mode

Visualising more complex situations with console.group

If you get into a situation where you have a lot of complex levels in your code, you can start logging like this:

const greetingsIn = [
  { language: 'English', greetings: ['hello', 'hi'] },
  { language: 'Spanish', greetings: ['hola', 'Buenas'] },
];

console.log('Starting the loop');
greetingsIn.forEach((opt) => {
  console.log(opt.language);
  opt.greetings.forEach((greeting) => {
    console.log(greeting);
  });
});

// Outcome:
// Starting the loop
// English
// hello
// hi
// Spanish
// hola
// Buenas
Enter fullscreen mode Exit fullscreen mode

It already gives you some idea of what is happening inside of the code, but if you really want more visual help, this might be a neat trick:

const greetingsIn = [
  { language: 'English', greetings: ['hello', 'hi'] },
  { language: 'Spanish', greetings: ['hola', 'Buenas'] },
];

console.log('Starting the loop');
console.group();
greetingsIn.forEach((opt) => {
  console.log(opt.language);
  console.group();
  opt.greetings.forEach((greeting) => {
    console.log(greeting);
  });
  console.groupEnd();
});
console.groupEnd();

// Outcome:
// Starting the loop
//   English
//     hello
//     hi
//   Spanish
//     hola
//     Buenas
Enter fullscreen mode Exit fullscreen mode

Need more?

If you want to know what you can do with console, check out its documentation on MDN.

There are a bunch of interesting features available that I didn't get to in this post, amongst which console.trace(), console.time() and the classics like info, warn and error.
I hope this made your next debugging session easier!

Top comments (0)