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 -
After using console.table()
it will appear like -
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 -
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");
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 -
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 -
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.