Console in JS other than console.log()

neel_dedhia

Neel Dedhia

Posted on December 29, 2021

Console in JS other than console.log()

Hey JS folks, we all have been using a very popular method console.log() for things apart from genuine logging. Most of us, once in a lifetime would have come across all the methods console object has to offer apart from console.log(), despite these we still tend to use .log() at times!

Today, once again when I went through the console object docs on MDN, a thought crossed my mind, what could be the reason we aren't adaptable to the other method in normal scenarios?

To get a better insight on this, I had initiated a poll on LinkedIn to ask my connections their thought and here are the results.

Linkedin Poll

From the results, it is seen that majority of people have found console.log() easy and quick to use. But, all these votes indirectly hint at one answer that is Unawareness. How? let me explain to you…

One uses any method which is either well known or has seen them the most while learning (this makes us easy & quick to re-use in real scenarios) the best example for this could be "variable i in loops".
If one is unaware of the ability of a function and how can it make your code robust and look good, then one may never find it needful in using.

The console.log() is only to put a message which is not strongly bound to the logical part of the code, it can be used as an affirmation to something. Eg: "User landed homepage from google-search". The other methods offered by the console are bound to specific usage under special scenarios. Using them increases our code & console readability.

Let me show you a few methods which have real meaning and application and I hope it would help you to switch from console.log() then onwards.

1. console.count() & console.countReset()

Let's assume you want to keep a count of how many click the user makes on the button. The code with .log() might look like this 👇

let userClickCounter = 0;
function watchUserClicks(){
  userClickCounter++;
  console.log(`User Clicked ${userClickCounter}`);
}
function resetCounter(){
  userClickCounter = 0;
  console.log("User Clicked reset");
}
</script>
<button onclick="watchUserClicks()">Click Me to without pause</button>
<button onclick="resetCounter()">Reset me if you pause</button>
Enter fullscreen mode Exit fullscreen mode

Now. let me show you the other way 👇

function watchUserClicks(){
  console.count(`User Clicked`);
}
function resetCounter(){
  console.log("User Clicked");
}
</script>
Enter fullscreen mode Exit fullscreen mode

Here the need for variable and its related code is eliminated thereby, making the code optimal and readable.

2. console.dir()

This method shows all the properties of the JS Object. The console.log() prints out toString representation whereas console.dir() prints out a navigatable tree. Check out the difference below 👇

console.dir() vs console.log() output

This method comes to the real help when you want to show a single Dom Element like this 👇

Dom Element in console.dir() and console.log()

3. console.trace()

If you are working on a very complex code architecture wherein the function you are writing has multiple call sources(it can be called from various methods directly or indirectly). You're function isn't working for some scenario and you don't who is the one calling and how is it called at caller's end. The trace() method will come to the rescue and help you getting to know trace of origin of this function call. This would save your tones of time about getting to know the code architecture just for one single call messing up. Let's see this with the example below👇

const myTask = (task) => youDoIt(task);
const youDoIt = (task) => letJuniorDoIt(task);
const letJuniorDoIt = (task) => forwardToFriend(task);
const forwardToFriend = (task) => forwardToLoyalFriend(task);
const forwardToLoyalFriend = (task) => {
 if(!!task){
  console.log('Worked on task: ' + task);
 }
 else{
  // !! will convert undefined, null, false, 0, '',  into false
  console.trace('Invalid task to work on'); 
 } 
}
// You aren't aware of where these lines are written in the project
myTask('Priority Task');
forwardToFriend('Bug in the code');
letJuniorDoIt('Easy Task');
forwardToLoyalFriend('Job Saver task');
youDoIt('');
Enter fullscreen mode Exit fullscreen mode

Let's see how trace() method helps you here:

Example of console.trace() method

4. console.time() and console.timeEnd()

When you are working on a complex algorithm, time is one of the main factor you need to look on simultaneously. This is where you can use these console methods to know how much time your algorithm is taking to execute.

function Factorial(n) {
    let fact=1;
    console.time('Calculate Factorial');
for (let i = 2; i <= n; i++){
        fact = fact * i;
    }
console.timeEnd('Calculate Factorial');
    return fact;
}
Enter fullscreen mode Exit fullscreen mode

Factorial in JS with console.time() & console.timeEnd()

5. console.table()

The best method vs console.log() to show an object in JS. This method is used to represent complex objects or arrays in tabular format. This method takes away all the hard work of inspecting at an object that console.log gives. With .table() you can easily view the objects sort them based on columns and traverse through.

const teamData = {
    Lead: {
        id: 'L01',
        firstname: "John",
        email: "john@gmail.com"
    },
    manager: {
        id: 'M01',
        firstname: "Alice",
        email: "aliceInwander@gmail.com"
    },
    developer: {
        id: 'D01',
        firstname: "Bob",
        email: "bobthebuilder@gmail.com"
    },
    tester: {
        id: 'T01',
        firstname: 'Dexter',
        email: 'dexterLab@gmail.com'
    }
}
console.table(teamData);
Enter fullscreen mode Exit fullscreen mode

console.table() to show team data

This method also gives a cherry for the cake. You can print selective columns from an object like below 👇

console.table(teamData, ['id', 'email']);
Enter fullscreen mode Exit fullscreen mode

Console.table with specific columns

There are other methods too and I would like to get to know from you which other methods you find are insightful and better than using console.log. Let me know if you need part 2 of this article discussing the rest of the methods console object has to offer.

I hope this read was fruitful and now you won't fall in any of the voting options that I had mentioned at the beginning. Share this article with your friends and colleagues at work, to make them aware of the hidden gems JS console has and make their life easier too.

Lastly, introducing myself

Hey 👋 I'm Neel Dedhia, a full-stack web developer I like to write articles about concepts that are odds but yet important towards growth in knowledge in tech. Also, I like to give and share my knowledge with my connections to mutually grow here with updated resources. If you like reading this article and looking forward to seeing more or to discuss with me on such topics, you can follow me here or connect me from the below sources:
Portfolio - http://neeldedhia.bio.link/
Linkedin - https://www.linkedin.com/in/neel-dedhia/
Twitter - https://twitter.com/neel_dedhia
Dev.to - https://dev.to/neel_dedhia
Instagram - https://instagram.com/arsictography

Thank you! for reading till this end, wish you all a Merry Christmas and Happy New Year!

💖 💪 🙅 🚩
neel_dedhia
Neel Dedhia

Posted on December 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related