Difference between console.dir and console.log in javascript?



In JavaScript, dir() and log() are the methods of console object. Console object provides access to the browser’s debugging console.

The console.dir() method

The console.dir() method output the list of object properties of a specified object in the console to the user. It recognizes the object just as an object and outputs its properties. console.dir shows all properties of a DOM element and can display only one object.

Syntax

The below syntax is for console.dir method.

console.dir(object)

Example

Following is an example of the console.dir() method in JavaScript −

console.dir(673563); console.dir("Welcome to Tutorialspoint"); console.dir(76325 * 476);

The console.log() method

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

Syntax

The syntax below is for console.log method.

console.log(value);
console.log("string", value);

Example

Following is an example of the console.log() method in JavaScript −

console.log(123); console.log("Hello Friends"); console.log(10 + 20);

In the above example, the console.log shown the output as we discussed at the beginning of the session. But here 10+20 the output is 30. Behind the debugging of that line it automatically summed up the integers and shown the respective sum of those integers.

Difference between console.dir() & console.dir()

The main difference between these two methods is that the console.log() method displays the “toString” representation of any object passed to it.

Whereas, the console.dir() method displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

Example 1

Following example demonstrates the usage of the console.log() and console.dir() methods in JavaScript −

let array=[9,6,4,2,5]; console.log("Result of console.log: ", array) console.log("Result of console.dir: ", array)

In this example the output for the array console.log and console.dir performed similarly. That both methods showing the number of objects in the array along with array elements.

Example 2

Following is another example of this −

var s = "Tutorials Point" var employee = { name: "Ganesh", role: "Manager", salary: "5000" }; var a = [10, 20, 30]; console.log(s); console.dir(s); console.dir(employee); console.log("employee with console.log = ", employee); console.dir(a); console.log("a with console.log = ", a); console.dir("a with console.dir = ", a);

Advertisements