Use console.table() instead of console.log()

Use console.table() instead of console.log()

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

Screen Shot 2021-08-28 at 7.28.08 PM.png

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

Screen Shot 2021-08-29 at 8.03.49 AM.png

If we just console.log(friends) this would show up.

Screen Shot 2021-08-29 at 8.08.13 AM.png

You tell me which you prefer. To me, console.table(friends) is significantly clearer.

Screen Shot 2021-08-29 at 8.06.22 AM.png

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')

Screen Shot 2021-08-29 at 9.44.08 AM.png

When to use console.table()

  1. I have an array of objects.
  2. Returning data from a SQL SELECT statement.
  3. Want to visualize our data set in a tabular format.

Advantages of using console.table() over console.log()

  1. More organized
  2. Easier to see your data
  3. 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