Different types of console statements in JavaScript

Different types of console statements in JavaScript

ยท

3 min read

Hello everyone ๐Ÿ‘‹, I'm back with another blog post where I'll be explaining the different types of console statement in JavaScript. As a developer, we all have seen the common console statement which is - console.log() but there are other types of console statements as well which can be helpful while debugging a code. In this blog, we'll be learning about them. โšก๏ธ

Lets's go

1. console.table();

This statement will help us to visualize our data in the console in a tabular manner. For example, when you try to console an array using console.log() it will be displayed like -

Screenshot 2021-01-23 at 4.10.48 PM.png

After using console.table() it will appear like -

Screenshot 2021-01-23 at 4.10.33 PM.png

2. console.trace()

This statement will help us to trace how the code ended up at a certain point. For example when you execute this -

function outerFn() {
  function innerFn() {
    console.trace();
  }
  innerFn();
}
outerFn();

The output in the console will be -

Screenshot 2021-01-23 at 4.17.19 PM.png

This shows the execution of the code in the reverse order. The code was executed in the following manner - outerFn() -> innerFn().

3. console.assert()

This statement is useful when you are trying to debug a boolean value. This will log only when the value is false. Let's consider an example -

let valid = false;
console.log(valid, "The valid parameter is false");

Screenshot 2021-01-23 at 5.10.47 PM.png

The syntax for this statement is - console.log(assertion, message)

4. console.dir();

This is one of my favourite console statements. If you are new to JavaScript and want to understand the concept of Closure this statement will help you a lot. This will show all the variables accessible in all the scopes in a particular function. Let's consider an example -

Screenshot 2021-01-23 at 5.31.12 PM.png

This is an example of closure. num variable will be accessible inside the addOne function. To check this we can use console.dir() function.

The output will be -

Screenshot 2021-01-23 at 5.33.51 PM.png

As we can see the variable num is present in the closure scope of the addOne function.


That's all for this blog ๐Ÿ˜.

I hope you liked this post. Happy Learning โšก๏ธ

Follow me on Twitter, GitHub and LinkedIn for more content related to Web Development.

Did you find this article valuable?

Support Apoorv's Blog by becoming a sponsor. Any amount is appreciated!