DEV Community

Cover image for Why using just console.log in 2023 is a big no-no 🚀
Al - Naucode
Al - Naucode

Posted on

Why using just console.log in 2023 is a big no-no 🚀

Here are 5 must-know console object methods and tricks!

Are you still using console.log for all your JavaScript debugging needs in 2023?

It's time to upgrade your skills and discover the full power of the JavaScript console object.

From console.table to console.time, these advanced methods and tricks will help you improve the quality and readability of your debug output and make it easier to troubleshoot and fix problems in your code.

So why not join the ranks of the JavaScript ninja debuggers in 2023, and learn these essential techniques? Your code will thank you.

😞 The problem

One of the biggest problems with using just console.log is that it can clutter up your code and make it difficult to read. Additionally, it's not very informative on its own. It just outputs the value of whatever you pass to it without any context or additional information.

With that in mind, here are ten JavaScript console object methods and tricks you should know about (and give them a try; I know it is faster to just console.log, but it can make your debugging experience way better, do it for your future yourself!).

1️⃣ console.table

This method allows you to output tabular data in a readable and easy-to-understand format. Instead of just logging out an array or object, console.table will display the data in a tabular format, which makes it easier to scan and understand.

// Output an array of objects as a table
const users = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Doe' }
];
console.table(users);
Enter fullscreen mode Exit fullscreen mode

This will output the users array in a tabular format, with the properties of each object as columns and the objects as rows.

console.table

2️⃣console.group

console.group and console.groupEnd. These methods allow you to create a nested, collapsible group in the console. This can be useful for organizing and structuring your debug output, so you can easily see what's happening at different levels of your code.

console.group('User Details');
console.log('Name: John Doe');
console.log('Age: 32');
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

This will create a nested, collapsible group in the console with the heading “User Details.” The log messages inside the group will be indented and grouped together.

console.group

3️⃣console.time

console.time and console.timeEnd. These methods allow you to measure the amount of time it takes for a block of code to execute. This can be useful for identifying performance bottlenecks in your code and optimizing them.

console.time('Fetching data');
fetch('https://reqres.in/api/users')
  .then(response => response.json())
  .then(data => {
    console.timeEnd('Fetching data');
    // Process the data
  });
Enter fullscreen mode Exit fullscreen mode

This will measure the amount of time it takes to fetch data from the specified URL and parse the JSON response. The elapsed time will be output in the console.

console.time

4️⃣console.assert

This method allows you to write assertions in your code, which are statements that should always be true. If an assertion fails, console.assert will output an error message in the console. This can be useful for catching bugs and ensuring your code is working as expected.

function add(a, b) {
  return a + b;
}

// Test the add function
const result = add(2, 3);
console.assert(result === 5, 'Expected 2 + 3 = 5');
Enter fullscreen mode Exit fullscreen mode

This will output an error message in the console if the add function does not return the expected result of 5 when given the input 2 and 3.

console.assert

5️⃣Style your logs

Use the console object to output styles and colors. The console object allows you to output text in different colors and styles, making your debug output more readable and easier to understand.

You can use the %c placeholder in your console.log statements to specify a CSS style for the output text.

console.log('%cHello world!', 'color: red; font-weight: bold;');
Enter fullscreen mode Exit fullscreen mode

This will output the text “Hello world!” in red and bold, using the specified CSS style.

Styling the console.log output with CSS

By the way, if you want even better logs, you might want to use a specialized logging library, which offers more settings. I added a really good one in this article I wrote: https://dev.to/naubit/5-small-and-hidden-react-libraries-you-should-already-be-using-nb5

6️⃣console.trace

Use the console.trace method to output a stack trace. This can be useful for understanding the flow of execution in your code and for identifying where a particular log message is coming from.

function foo() {
  console.trace();
}

function bar() {
  foo();
}

bar();
Enter fullscreen mode Exit fullscreen mode

This will output a stack trace in the console, showing the sequence of function calls leading up to the console.trace call. The output will look something like this:

console.trace

7️⃣console.dir

Use the console.dir method to output the properties of an object in a hierarchical format. This can be useful for exploring the structure of an object and for seeing all of its properties and methods.

const obj = {
  id: 1,
  name: 'John Doe',
  address: {
    street: '123 Main St',
    city: 'New York',
    zip: 10001
  }
};
console.dir(obj);
Enter fullscreen mode Exit fullscreen mode

This will output the properties of the obj object in a hierarchical format, allowing you to see the structure of the object and all of its properties and values.

console.dir

8️⃣console.count

Use the console.count method to count the number of times a specific log message is an output. This can be useful for keeping track of how many times a particular code path is executed and for identifying hot spots in your code.

function foo(x) {
  console.count(x);
}

foo('hello');
foo('world');
foo('hello');
Enter fullscreen mode Exit fullscreen mode

This will output the string “hello” in the console, followed by the number 1. It will then output the string “world” in the console, followed by the number 1. Finally, it will output the string “hello” again, followed by the number 2 (since it has been called twice).

console.count

9️⃣console.clear

Use the console.clear method to clear the console output. This can be useful for keeping your debug output organized and uncluttered and for making it easier to focus on the information you're interested in.

console.log('Hello world!');
console.clear();
console.log('This log message will appear after the console is cleared.');
Enter fullscreen mode Exit fullscreen mode

This will output the string “Hello world!” in the console, followed by a blank line (since the console is cleared). It will then output the string “This log message will appear after the console is cleared.”

console.clear

1️⃣0️⃣console.profile

Use the console.profile and console.profileEnd methods to measure the performance of a block of code. This can be useful for identifying performance bottlenecks and for optimizing your code for speed and efficiency.

console.profile('MyProfile');

// Run some code that you want to measure the performance of
for (let i = 0; i < 100000; i++) {
  // Do something
}

console.profileEnd('MyProfile');
Enter fullscreen mode Exit fullscreen mode

This will start profiling the block of code between the console.profile and console.profileEnd calls and will output the results in the console when the console.profileEnd call is executed. The output will include details about the amount of time it took to execute the code and any other performance-related information.

console.profile

💭 Some final thoughts

In 2023, don’t just settle for console.log - there are many more powerful and valuable tools and techniques available in the JavaScript console object.

From console.table to console.time, these methods and tricks will help you improve the quality and readability of your debug output, and make it easier to troubleshoot and fix problems in your code.

So why not level up your debugging skills in 2023 and give these techniques a try? Your code (and your sanity) will thank you.

Oh, and…

🌎 Let’s Connect!

Top comments (49)

Collapse
 
leob profile image
leob

Great article, useful to know, but console.log isn't a "big no-no" at all, it just depends on how you use it - most of the time I just use it as a temporary statement to debug something, and when I'm done I delete it from my code :)

Collapse
 
leober_ramos33 profile image
Leober Ramos

Marketing bro, you have to know how to sell your post. Also, the man tries to talk about people who only use "console.log" and don't know the other methods that the JavaScript "console" object has.

But yes, console.log is also a good method and can be used together with these others, since although the others are good, for example to print any type of data on the console (boolean, object, string, etc.) it's better to use console.log.

Collapse
 
leob profile image
leob

Yeah you're right, the "big no-no" makes for a catchy title, it draws attention ... well yes, I purely insert console.log's to dump a piece of data in order to debug an issue, once I've solved it my console.log statement will be promptly deleted from the code ... anyway, these new console methods are definitely cool!

Thread Thread
 
naucode profile image
Al - Naucode

Yeah, most people most of the time (even myself) will continue using the console.log. It is not a bad thing. This is just a way to raise some attention in other methods that sometimes we can use. I like to use for example the time and assert ones.

Thread Thread
 
leob profile image
leob

I've used the time one as well, it's great (to time a piece of 'synchronous' JS code)

Collapse
 
radualexandrub profile image
Radu-Alexandru B

Yes logging is very okay.
However in my most scenarios I just use console.debug() and console.error() instead (so most of the logging will be invisible to the end user -> "verbose" mode should be enabled in order to see the debug logs).

Here's an example of how I use logging most of the times:

  onBuildUrl(urlNewForm: NgForm) {
    const methodName = 'onBuildUrl()';

    console.debug(
      `${methodName} urlNewForm ${JSON.stringify(urlNewForm.value)}`
    );
    try {
      this.urlNew = new URL(urlNewForm.value.href);
      console.debug(`${methodName} New URL ${this.urlNew}`);
    } catch (error) {
      console.error(
        `${methodName} ${urlNewForm.value.href} is not a valid URL - ${error}`
      );
    }
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leob profile image
leob

Yeah that could be very useful, especially if you could make the logs available in a production app (that would require some sort of periodic Ajax call to sync the logs to a backend) ... I assume that console.debug has negligible overhead if it's disabled/non-verbose?

Thread Thread
 
radualexandrub profile image
Radu-Alexandru B • Edited

Yes, that's right. In production we should not only use console.log/debug/anything as they're only accessible on end-user's browser... instead, we should (also) use a proper Node.js logging library (that could provide full timestamps as well), such as the ones mentioned on this StackOverflow thread. (Also keep in mind that some apps should never use console.logging in the browser, as sensitive information could be shown/accessible by end user)

Also on end-user's browser, console.debug are still written on the console (eg. DevTools), but they are just not visible if "Verbose" is not checked from options.

Collapse
 
walze profile image
wallace fares

Yea I was gonna say the same thing, other than the cringy click baity title, the article is good as well

Collapse
 
brense profile image
Rense Bakker

Console assert is awesome! Doesn't polute your console when everything is running fine and gives you enough data to debug when something goes wrong

Collapse
 
naucode profile image
Al - Naucode

Yeah! It is a really good method

Collapse
 
liftoffstudios profile image
Liftoff Studios

Or better yet, Don't use console methods 😬, use the inbuilt browser debugger :)

Collapse
 
naucode profile image
Al - Naucode

Even better! Although I find myself going back always to the usual console functions 😂

Collapse
 
devoskar profile image
Oskar Pietrucha

I just prefer to set a debugger and then do everything inside the Dev Tools and next on copy the insights to my code.
I think it's just I have a bigger overview on what is currently happening inside the app and browser.
I don't use console.log at all

Collapse
 
dvddpl profile image
Davide de Paolis • Edited

nice and very well written post.

using just console.log in 2023 is a big no no

it was already in 2020, and 2015... because you should debugging using other other tools!
these tricks are nice and neat (and definitely helpful sometimes) but if you really want to sharpen your axe please use a proper debugger and breakpoint (and conditional breakpoints) .

Collapse
 
nazim47 profile image
Nazim Ansari

Great post! I totally agree that using just console.log in 2023 is a big no-no. With the rapid advancements in technology and the abundance of better debugging tools available, relying solely on console.log is not only inefficient but also outdated. Using more advanced debugging tools not only helps us find and fix errors faster, but also allows us to gain a deeper understanding of our code. Thanks for bringing this important topic to light!

Collapse
 
polaroidkidd profile image
Daniel Einars

Oh man, those are a bunch of really useful console loggers! I knew some of them but not all!

Going to have to update my postfix completions

Collapse
 
naucode profile image
Al - Naucode

Thanks for the amazing comment! I was also amazed when I found all of them!

Collapse
 
moibra profile image
Mohamed Ibrahim

Awesome, Very useful article

Collapse
 
israelortuno profile image
Israel Ortuño

Very great article

Collapse
 
kenslearningcurve profile image
Kenji Elzerman

I don't use front-end much in my work, but when I do I hate the Console.log. This article is awesome and learned me a lot!

Collapse
 
naucode profile image
Al - Naucode

Thank you for the awesome comment!

Collapse
 
sdedrov profile image
Seth Dedrov

very useful

Collapse
 
alptekin profile image
m-alptekin

Thanks. I was already using time console.time to have an idea on performance but for others I either had not used or didn’t know about… definitely a very beneficial content.

Collapse
 
naucode profile image
Al - Naucode

Thank you! Yeah, time is really useful. I also like the assert one.

Collapse
 
ismailco96 profile image
ismail courr

Great article, Thanks for sharing

Collapse
 
giadat1599 profile image
giadat1599

Nice post, those are really useful console loggers.

Collapse
 
naucode profile image
Al - Naucode

Thanks!

Collapse
 
daohuyhoang9119 profile image
Dao Huy Hoang

Very awesome broo

Some comments may only be visible to logged-in visitors. Sign in to view all comments.