Unleashing the Power of console.log() in JavaScript

Maybe you’re probably familiar with console.log(). It’s a simple and powerful tool that can be used to print messages to the browser console, which is an essential tool for debugging and troubleshooting your code.

But did you know that console.log() has a lot more to offer than just printing messages to the console? In this article, we’ll explore some of the advanced capabilities of console.log() and how you can use them to make your debugging and troubleshooting experience even better.

Logging Objects

One of the most common use cases of console.log() is logging strings and numbers. But did you know that you can also log objects? When you pass an object to console.log(), it will print out the object’s properties and values. This can be incredibly useful when you’re debugging complex objects or trying to figure out what’s going wrong with your code.

JavaScript
const person = {
  name: 'John',
  age: 30,
  job: 'Developer'
}

You can log this object to the console by simply passing it to console.log():

JavaScript
console.log(person);

This will print out the object’s properties and values in the console, making it easy for you to see what’s going on.

Styling Console Output

Did you know that you can style the output of console.log()? This can be especially useful when you want to highlight certain messages or make them stand out from the rest of the console output.

To style console output, you can use CSS-like syntax. For example, you can add a background color and font color to your message like this:

console.log('%c Hello World! ', 'background: #000000; color: #badada');

Using console.table()

Another useful method that you can use with console.log() is console.table(). This method takes an array of objects and prints them out as a table in the console. This can be incredibly useful when you’re working with large datasets or trying to visualize complex objects.

JavaScript
const people = [
  {
    name: 'John',
    age: 30,
    job: 'Developer'
  },
  {
    name: 'Jane',
    age: 25,
    job: 'Designer'
  },
  {
    name: 'Bob',
    age: 40,
    job: 'Manager'
  }
];

You can print out this array as a table by using console.table():

JavaScript
console.table(people);

This will print out the array as a table in the console, which can be incredibly helpful when you’re trying to visualize the data.

Using console.time() and console.timeEnd()

The console.time() and console.timeEnd() methods can be used to measure how long it takes for a piece of code to run. This can be useful when you’re trying to optimize your code and want to see which parts are taking the longest to run.

JavaScript
console.time("myFunction");
for(i=0;i<100000000;i++){};
console.timeEnd("myFunction");

This will output the time it took for the code between console.time() and console.timeEnd() to run.

Debugging with console.error()

When something goes wrong with your code, it can be frustrating to figure out where the problem is occurring. Console.error() is a powerful tool that can help you quickly identify errors in your JavaScript code.

To use console.error(), simply pass in a message as a string or as an object. The message will then be printed to the console with an error icon, making it easy to spot.

JavaScript
const x = 5;
const y = "foo";
if (typeof x !== "number") {
  console.error("x is not a number");
}
if (typeof y !== "number") {
  console.error("y is not a number");
}

In this example, we’re checking whether x and y are numbers. If they’re not, we’re logging an error message to the console using console.error(). This makes it easy to quickly identify the source of the problem, even in a large codebase.

Debugging with console.assert()

The console.assert() method is used to test if an expression is true, and if it isn’t, it will throw an error message to the console. This can be helpful for debugging to ensure that certain conditions are met.

JavaScript
const x = 5;
console.assert(x === 10, "Error: x is not equal to 10");

In this example, since x is not equal to 10, the console will output the error message “Error: x is not equal to 10”.

Using console.assert() can help catch errors early on in development and make debugging easier.

Debugging with console.group()

Sometimes, when debugging complex code, it can be difficult to keep track of which console logs correspond to which parts of the code. This is where console.group() comes in handy.

console.group() allows you to group related console logs together under a single collapsible heading in the console. This can make it easier to see the flow of the code and find where the issue is occurring.

JavaScript
function calculateTotalPrice(products) {
  console.group('calculateTotalPrice function');
  console.log('Products:', products);

  let totalPrice = 0;
  for (let i = 0; i < products.length; i++) {
    const product = products[i];
    console.group('Product ' + (i + 1));
    console.log('Name:', product.name);
    console.log('Price:', product.price);
    totalPrice += product.price;
    console.groupEnd();
  }

  console.log('Total Price:', totalPrice);
  console.groupEnd();
  return totalPrice;
}

const products = [
  { name: 'Shirt', price: 20 },
  { name: 'Pants', price: 30 },
  { name: 'Shoes', price: 50 }
];

calculateTotalPrice(products);

In this example, we have a function that calculates the total price of an array of products. We use console.group() to group related console logs together for each product in the array. This makes it easy to see which product corresponds to which logs, and allows us to collapse and expand the groups as needed.

console.group() also has a companion method, console.groupCollapsed(), which creates a collapsed group by default. This can be useful when you have a lot of logs to group together and want to keep the console tidy.

Overall, console.group() is a powerful tool for debugging complex code and can make the process much more efficient.


In this article, we have explored some of the methods and possibilities of using the JavaScript console for debugging and optimizing code.

However, there are many other functions and features that you can experiment with to find what works best for you.

By utilizing the power of console.log() and its various methods, you can greatly improve your productivity and efficiency as a JavaScript developer. It’s an essential tool that can save you time and frustration while debugging.

So, next time you work on a JavaScript project, remember to make the most out of console.log() and happy debugging !

Similar Posts