console.log
is one of the most versatile functions in JavaScript. You can use it for debugging, check the value of a variable, print "Success" to check if your function will fire and much more. But did you know how many more features console has past logging x value?
console.table()
If you have tabular data such as an object or an array and want to organize view of your data, especially an object or an array, you can use console.table()
.
As an example, we have an object of user details.
const userDetails = {
first_name: "John",
last_name: "Doe",
email: "johndoe@gmail.com",
phone_number: "999-555-5555",
age: 28
};
console.table(userDetails)
Returned
Ok nice, but I could've easily just console.log that and thats true. So not as useful with objects. But where it really becomes organized is when you're logging out tables / arrays. Let me give you another example.
Let's say you are returning an array of objects.
const friends = [
{
first_name: "John",
last_name: "Doe",
email: "johndoe@gmail.com",
phone_number: "999-555-5555",
age: 28
},
{
first_name: "Jane",
last_name: "Doe",
email: "janedoe@gmail.com",
phone_number: "999-333-3333",
age: 25
},
{
first_name: "Jeff",
last_name: "Deff",
email: "jeffdeff@gmail.com",
phone_number: "111-222-3333",
age: 22
}
]
console.table(friends)
Returned will look something like this
If we just console.log(friends) this would show up.
You tell me which you prefer. To me, console.table(friends) is significantly clearer.
Level up
Ok what happens if we only need to see the first_name from our array of friends. console.table()
can take 2 parameters. For example, we can call console.table(friends, 'first_name')
. The second parameter will be whatever column we want to get. This is very powerful when we have an array of objects.
Using the sample array of friends from above, let's just get the first_name of all of our friends.
console.table(friends, 'first_name')
When to use console.table()
- I have an array of objects.
- Returning data from a SQL
SELECT
statement. - Want to visualize our data set in a tabular format.
Advantages of using console.table()
over console.log()
- More organized
- Easier to see your data
- Sort your data easier
Conclusion
There is a lot of methods that you can use with the console
api. Today I shared with you console.table()
. I hope you learned something new. Let me know in the comments below how you use console.table
If you want to learn more about console.table() visit https://developer.mozilla.org/en-US/docs/Web/API/console/table