Open In App

Difference Between console.dir and console.log

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Console Object

The Console object provides access to the browser's debugging console, which can be seen using F12 or ctrl+shift+j. Console object contains many methods, log() and dir() are the most used among them.

Console.log:

The console.log() method prints out a toString representation of the object in the console to the user.

Syntax:

console.log(object) or console.log("string", object)

Console.dir:

The console.dir() method output the list of object properties of a specified object in the console to the user.

Syntax:

console.dir(object)

In simple words, the console.log() returns the object in its string representation and console.dir() recognizes the object just as an object and outputs its properties. Both log() and dir() returns the string just as a string.

Example:

javascript
let str = "Howdy GeeksforGeeks";
let geek = {
    book: "harrypotter",
    price: "2000"
};
let geek2 = [10, 20, 30];

console.log(str);
console.dir(str);
console.dir(geek);
console.log("geek (log) = ", geek);
console.dir(geek2);
console.log("geek2 (log) = ", geek2);

// Prints only string as dir() takes
// only one parameter.
console.dir("geek2 (dir) = ", geek2);

Output:

In the code above, console.log() prints the toString representation of the object, while console.dir() recognizes the object and displays its properties. When run in Chrome, console.log() outputs a tree structure along with the string information. However, in Firefox, console.log() only shows the toString representation, while console.dir() behaves consistently across browsers. For example, when you run console.dir("geek2 (dir) =", geek2);, it only displays the string part because console.dir() takes only one parameter, treating the string as the sole argument, whereas console.log() can accept multiple parameters.


Next Article

Similar Reads