Debugging beyond console.log() in JavaScript
Gautam Vaja

Gautam Vaja @mvaja13

About: Learner | Reader | Developer

Location:
Mumbai, India
Joined:
Jan 24, 2024

Debugging beyond console.log() in JavaScript

Publish Date: Jun 5 '24
195 18

Most JavaScript developers are familiar with the basic console.log(). However, the console API offers many other methods that can be incredibly useful in both development and debugging workflows.

Basic console.log()

Let's start with the basic console.log() which is used to print messages to the console.

console.log("Hello, World!");
Enter fullscreen mode Exit fullscreen mode


This is the most commonly used method for debugging and logging messages.

console.error()

console.error() is used to output error messages. It helps in distinguishing errors from regular log messages in the console.

console.error("This is an error message");
Enter fullscreen mode Exit fullscreen mode

This will print the message in red, making it stand out.

console.warn()

console.warn() outputs warning messages. These are less severe than errors but still important to notice.

console.warn("This is a warning message");
Enter fullscreen mode Exit fullscreen mode

Warning messages appear in yellow, which helps to differentiate them from regular logs and errors.

console.info()

console.info() is used for informational messages.

console.info("This is an informational message");
Enter fullscreen mode Exit fullscreen mode

It behaves similarly to console.log() but can be useful for categorizing log messages.

console.debug()

console.debug() is used for debugging purposes and is often hidden by default in many browsers' console settings.

console.debug("This is a debug message");
Enter fullscreen mode Exit fullscreen mode

To enable it make sure that Verbose is checked in the top bar.

console.table()

console.table() allows you to display data as a table. This can be very helpful when working with arrays or objects.

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 },
];

console.table(users);
Enter fullscreen mode Exit fullscreen mode

This will print the users array as a table, making it easier to read.

console.time() and console.timeEnd()

These methods are used to measure the time taken for a piece of code to execute.

function processData() {
  console.time("processData");
  // Simulating a time-consuming process
  for (let i = 0; i < 1000000; i++) {
    // Process
  }
  console.timeEnd("processData");
}

processData();
Enter fullscreen mode Exit fullscreen mode

console.time("processData") starts the timer, and console.timeEnd("processData") stops it, printing the time elapsed in milliseconds. This can help identify bottlenecks in code and improve performance.

console.count()

console.count() is used to count the number of times a code block is executed.

for (let i = 0; i < 5; i++) {
  console.count("Counter");
}
Enter fullscreen mode Exit fullscreen mode

This will print the count each time the loop runs.

console.group() and console.groupEnd()

These methods allow you to group together multiple log messages.

console.group("User Details");
console.log("Name: Alice");
console.log("Age: 25");
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

This creates an expandable group in the console. You can also create nested groups for better organization.

console.assert()

console.assert() writes a message to the console only if an assertion is false.

const x = 10;
console.assert(x > 10, "x is not greater than 10");
Enter fullscreen mode Exit fullscreen mode

Since x is not greater than 10, the message will be printed.

Styling Console Logs

You can style console log messages using CSS.

console.log("%cThis is a styled message", "color: blue; font-size: 20px;");
Enter fullscreen mode Exit fullscreen mode

The %c is a placeholder for the CSS style string that follows.

Best Practices

  1. Use Appropriate Methods: Use console.error() for errors, console.warn() for warnings, and so on. This helps in filtering messages in the console.
  2. Remove Logs in Production: Ensure that you remove or disable console logs in production code to avoid clutter and potential performance issues.
  3. Group Related Logs: Use console.group() and console.groupEnd() to keep related logs together.

Conclusion

Next time you’re knee-deep in code and need to debug, give these methods a try. They can make your life easier and your debugging sessions more efficient. So, go ahead, experiment with these in your next project and see the difference they can make.
For more detailed information, you can refer to the MDN Web Docs on console.

Comments 18 total

  • Saikumar
    SaikumarJun 6, 2024

    it's better to use logging libraries like errsole because you can get insights about your application and see your logs all in one place in the UI

  • David Bosah
    David BosahJun 6, 2024

    Nice

  • SUDIP MONDAL
    SUDIP MONDALJun 6, 2024

    Insightful

  • Adapaka Abhiram
    Adapaka AbhiramJun 6, 2024

    Thank you for sharing, Very insightful!

  • Shrijal Acharya
    Shrijal AcharyaJun 6, 2024

    Never knew about console.time(). Thank you for sharing this. 🙌

    • Anmol Baranwal
      Anmol BaranwalJun 7, 2024

      Yep! Didn't know a lot of stuff. Console hides a lot!
      I think using a separator after each point would give a better structure for the post.

  • pramon18
    pramon18Jun 6, 2024

    The console.counter() one is very useful.

  • Lin Fan-Chiang
    Lin Fan-ChiangJun 7, 2024

    Thank you for sharing. I plan to use console.group() and console.groupEnd() for my next implementation.

  • Mark
    MarkJun 7, 2024

    Thanks for sharing this with us! Keep up the good work.

    If you want to know more about java then do visit here

  • alBz
    alBzJun 7, 2024

    really nice Article ;-)

  • Krunal Rana
    Krunal RanaJun 7, 2024

    console.time() and console.timeEnd()

    is new for me #Helpfull #greateinsight

  • Krunal Rana
    Krunal RanaJun 7, 2024

    console.log(Object.keys(console))

    Try this you will get list of functions associate with console function,

    Alternat methods :

    Using Object.getOwnPropertyNames()
    console.log(Object.getOwnPropertyNames(console));

    Using for...in loop

    for (let key in console) {
    console.log(key);
    }

    *Note : * this is not just console function we can find almost all properties of any JS function

    Image description

  • Nancy Rosales
    Nancy RosalesJun 7, 2024

    HIRE A HACKER TO FIND AND RECOVER YOUR STOLEN BTC/ETH/USDT/NFT'S AND ALL TYPES OF DIGITAL ASSETS
    Someone I met online scammed me out of approximately $367,000 on a fictitious investment proposal. After I started looking for legal assistance to get my money back, I found a number of testimonials about WEB GENIE RECOVERY on www.webgenierecovery.com. I contacted them with all the information I needed, and it took the specialists around 72 hours to find and assist with getting my money back. I am quite relieved, and I hope that this will assist many others who have fallen prey to these fraudulent internet investment con artists. I heartily urge using the expert services to help with a quick and effective recuperation. Please get in touch with them at webgenierecoverys@proton.me.
    webgenierecovery@outlook.com
    via WhatsApp (918) 809-0113
    Telegram: @WEBGENIERECOVERY

    
    ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qekse6887bpeyfl70092.png)
    
    Enter fullscreen mode Exit fullscreen mode
  • Nancy Rosales
    Nancy RosalesJun 7, 2024

    HIRE A HACKER TO FIND AND RECOVER YOUR STOLEN BTC/ETH/USDT/NFT'S AND ALL TYPES OF DIGITAL ASSETS
    Someone I met online scammed me out of approximately $367,000 on a fictitious investment proposal. After I started looking for legal assistance to get my money back, I found a number of testimonials about WEB GENIE RECOVERY on www.webgenierecovery.com. I contacted them with all the information I needed, and it took the specialists around 72 hours to find and assist with getting my money back. I am quite relieved, and I hope that this will assist many others who have fallen prey to these fraudulent internet investment con artists. I heartily urge using the expert services to help with a quick and effective recuperation. Please get in touch with them at webgenierecoverys@proton.me.
    webgenierecovery@outlook.com
    via WhatsApp (918) 809-0113
    Telegram: @WEBGENIERECOVERY
    Image description

  • Alan Oberto
    Alan ObertoJun 8, 2024

    Very Nice article, I was not aware of at least half of it

  • Donelli
    DonelliJun 8, 2024

    cool article

  • cance
    canceJun 11, 2024

    Can we override console log in JavaScript?

Add comment