JS Tip of the Day: Expandable Logs With console.dir

Expandable Logs With console.dir
Level: Beginner

Hopefully by now you’re already probably quite familiar with the console.log() function (it’s used extensively within these tips). What it does is logs values to the JavaScript console. Depending on what a value is, however, you might see different ways of it getting displayed. Using Chrome as an example, if you log a function, you’ll see the letter “ƒ” followed by a lot, if not all, of the source code of that function or possibly something resembling [native code] if its a built-in. If you log an element, you’ll see the HTML element as one or more HTML nodes. And if you log an object, you’ll see an expandable version of that object that lets you dig down into its properties and methods including those that are inherited (via the __proto__ property).

console.log(function () { /* source */ });
// ƒ () { /* source */ }

console.log(document.body);
// <body></body>

console.log({});
// ► {} (<- expandable)

The expandable object variation is a great way to see what an object is made of. It can be very useful in learning more about an object and its type. But in the case of something like an HTML element, you may find that console.log() won’t give you the element in that format, instead only using the HTML representation. This is where console.dir() comes in to play.

console.dir() is a console logging method much like console.log() except that it will always provide you with the expandable object version of any object logged. So whereas console.log() will show an HTML element as HTML nodes, console.dir() will instead show it as a JavaScript object, thereby allowing you to dig down into the properties and methods of that element which isn’t possible with the HTML format.

console.dir(document.body);
// ► body (<- expandable)

More info: