Thursday, August 28, 2025
HomeLanguagesJavascriptDifference between console.dir and console.log

Difference between console.dir and console.log

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 most used among.

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)

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:




<!DOCTYPE html>
<html>
  
<head>
  
    <script>
        var str = "Howdy neveropen"
        var geek = {
            book: "harrypotter",
            price: "2000"
        };
        var 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);
    </script>
</head>
  
</html>


Output:

In the above code, log() prints the toString representation of the object while dir() recognizes the object and prints its properties only.

The above program is runned in chrome, so log() prints the tree along with the string info, but if runned in firefox log() only prints out toString representation info, while dir() behaves the same anywhere.

As you can see in the code console.dir(“geek2 (dir) = “, geek2); only prints the string part but not the object properties because dir() take only one parameter and considers the string as its only parameter passed into the methods, whereas log() takes any number of parameters.

RELATED ARTICLES

Most Popular

Dominic
32236 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6609 POSTS0 COMMENTS
Nicole Veronica
11779 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11828 POSTS0 COMMENTS
Shaida Kate Naidoo
6719 POSTS0 COMMENTS
Ted Musemwa
7002 POSTS0 COMMENTS
Thapelo Manthata
6678 POSTS0 COMMENTS
Umr Jansen
6690 POSTS0 COMMENTS