JavaScript console.log vs console.dir
JavaScript, Web Design
So what is the difference between console.log and console.dir in JavaScript? Well, let’s take a look! If we were to take this code:
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>console.log vs console.dir</title>
</head>
<body>
<script>
console.log(“Why, hello!”);
console.dir(“Why, hello!”);
</script>
</body>
</html>
then put it in a text editor, then run it in a browser we would get a blank page. That is because when we use these commands, they are only viewable in the console itself. So to see what these commands actually do we need to right-click the page in Chrome or Firefox and choose the inspect option then the developer tools come up. On a PC you can press F-12 and that will bring it up as well. From there you can click on the console tab if it isn’t already selected:
Once you select the console tab you’ll see that console.log and console.dir write whatever it is that you defined to the console window:
When you are printing text to the console, they do exactly the same thing. They take the string (text) you’ve given the code and display it out on the console. The difference comes in when you write out more complicated JavaScript items to the console like objects or arrays. Take this code for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>console.log vs console.dir</title>
</head>
<body>
<script>
console.log({name:”Dave”, job:”Trainer”, patronus:”sloth”});
console.dir({name:”Dave”, job:”Trainer”, patronus:”sloth”});
</script>
</body>
</html>
Now that I’m using an object, console.log and console.dir’s differences start to stand out. Here is what we get in the console:
We can see that console.log still just prints out the object as a string, but console.log recognizes it as an object. They both allow you to drop down and navigate the object’s key-value pairs so yeah, to be honest, not a lot of difference here. If you want to learn more check out our JavaScript Training.