console.dir vs console.log: 3 Main Difference
In this article, we will discuss the 3 main differences between console.log and console.dir.
The use of console is limitless you can even use it to track the performance of your application.
2 of such methods of console object are console.log and console.dir about which we are going to discuss in this article and also discuss the difference between them.
The elements of the console are displayed in the order in which they are logged. The console is not cleared after each log by itself. However, you can clear the console by using the console.clear() method.
The DOM element that you log using console.log is interactive. You can click on it to interact with it.
It can accept multiple objects or messages at a time.
console.log(123);//number console.log("Hello World!");//string console.log(10 + 20);//expression console.log(new Date());//object
console.dir method is used mainly to display properties of an object. It outputs the list of properties of an object in a readable and interactive manner.
'dir' in the console.dir stands for the directory which represents the listing of elements or objects properties.
var arr = [1,2,3,4,5]; console.dir(arr); console.dir(document.location);
console.dir vs console.log
- Reference to object: console.log takes direct reference of the object it is logging while console.dir makes a copy of the object before logging.
- DOM interaction: Using console.log you can interact with document objects (DOM) but using the console.dir you can not.
- Output type: console.log prints the object in an HTML like a tree while console.dir prints the element in a JSON like a tree.
- Output order: console.log prints the elements in the order in which they are logged while console.dir prints the elements in alphabetical order.
Here is an example that shows the output difference between console.dir vs console.log.
const arr = [1, 2, 3, 4, 5]; console.log(arr); console.dir(arr); console.log(document.head); console.dir(document.head);
Use console.log to display the output of anything in the console including strings, numbers, objects, etc. Use console.dir if you want to display the properties of an object in a hierarchical manner in JSON like format.