console.log vs console.dir in JavaScript

Both console.log() and console.dir() are built-in JavaScript methods used for debugging in web developer consoles, but they display data differently. While console.log() outputs a general, often formatted string or HTML-like representation of an object, console.dir() provides an interactive, expandable list of an object’s properties and methods. Understanding their distinct behaviors—especially when working with Document Object Model (DOM) elements—helps developers inspect JavaScript structures more effectively.


What is console.log()?

console.log() is the most common logging method in JavaScript. It prints the parameter passed to it in a human-readable format. When passed an object, it outputs a formatted representation; when passed a DOM element, it prints the element as an interactive HTML tree.

const element = document.querySelector('h1');
console.log(element);
// Output: <h1>Heading Text</h1> (as an HTML element tree)

console.log() also supports string substitutions and CSS formatting:

console.log('%c Success!', 'color: green; font-weight: bold;');
console.log('User %s has %d points', 'Alice', 42);

What is console.dir()?

console.dir() stands for “directory.” It outputs an interactive, hierarchical listing of all properties of a specified JavaScript object. It treats any input strictly as a JavaScript object, ignoring custom representations like HTML tags.

const element = document.querySelector('h1');
console.dir(element);
// Output: HTMLHeadingElement { align: "", title: "", onclick: null, ... }

When you inspect a DOM node with console.dir(), you can view all underlying properties, methods, event listeners, and prototype chains attached to that element.


Key Differences

Feature console.log() console.dir()
DOM Elements Prints the element as an HTML tree. Prints the element as an interactive JavaScript object.
Plain Objects Displays expandable object contents (browser-dependent). Displays the exact property tree of the object.
String Formatting Supports substitutions (%s, %d, %c). Does not support formatting strings; accepts only an object.
Primary Purpose General logging and reading markup. Deep property and method inspection.

Summary of When to Use Which