search

Mastering JavaScript console.log()

console.log() is a fundamental function that plays a crucial role in debugging and monitoring code execution in JavaScript development. It allows developers to print messages, variable values, and other important information directly to the browser’s console.

This visibility into the code’s behavior helps in understanding issues more quickly and can significantly enhance your ability to diagnose and resolve problems in your code

In this guide i will cover various aspects of using console.log(), including basic usage, advanced techniques, and best practices.

Basic Usage

The simplest use of console.log() is printing values to the console – text, numbers, arrays, and objects:

console.log('Hello, World!');
console.log(42);
console.log([1, 2, 3]);
console.log({ name: 'Alice', age: 30 });

Here is how it looks in Chrome DevTools:

Chrome Developer console.log()

Debugging with console.log()

A common debugging pattern is printing variable values at different points in your code to trace execution flow:

let x = 10;
let y = 20;
console.log('x:', x);
console.log('y:', y);
let z = x + y;
console.log('z:', z);

This reveals the state of each variable at each step, making it easy to spot where a value goes wrong.

Print Multiple Values in One Call

Pass multiple arguments separated by commas to print them in a single line:

let name = 'Bob';
let age = 25;
console.log('Name:', name, 'Age:', age);

Format Console Output

The console supports string substitution for formatted output. Use %s for strings, %d for numbers, and %c for CSS styling:

console.log('Name: %s, Age: %d', 'Alice', 30);
console.log('%cThis is a styled message', 'color: blue; font-size: 20px;');

Formatted output makes it easier to spot specific values when debugging complex logic.

Template Literals

In modern JavaScript, template literals are often more readable than string substitution:

let user = 'John';
let score = 95;
console.log(`User: ${user}, Score: ${score}`);
console.log(`${user} scored ${score > 90 ? 'above' : 'below'} 90`);

Inspect Objects and Arrays

When debugging objects and arrays, console.log() prints their structure and content:

let person = { name: 'Charlie', age: 35 };
let numbers = [1, 2, 3, 4, 5];
console.log(person);
console.log(numbers);

For a more visual representation, console.table() displays data as a sortable table:

console.table(numbers);
console.table([person]);

Conditional Logging

Use conditions to control when messages appear. This is useful for toggling debug output without removing the statements:

let debug = true;
if (debug) {
  console.log('Debug mode is on');
}

Other Console Methods

The console object offers more than just log(). Here are the most useful methods:

// Severity levels
console.warn('This is a warning');
console.error('This is an error');
console.info('This is informational');

// Group related messages
console.group('User Details');
console.log('Name: Alice');
console.log('Age: 30');
console.groupEnd();

// Measure execution time
console.time('loop');
for (let i = 0; i < 1000000; i++) {}
console.timeEnd('loop'); // loop: 3.456ms

// Log only when a condition fails
console.assert(1 === 2, 'This will print because 1 !== 2');

// Output a stack trace
console.trace('Trace from here');

console.warn() and console.error() are especially useful because they produce distinct visual styles in the console (yellow for warnings, red for errors) and can be filtered separately in DevTools.

Remove console.log in Production

Debug statements should not ship to production. They can expose sensitive data and clutter the console for users. The cleanest approach is stripping them at build time.

If you use a bundler like Webpack or a framework like Next.js, configure it to remove console calls in production. For simpler setups, ESLint's no-console rule flags any console statements during development:

// .eslintrc.json
{
  "rules": {
    "no-console": ["warn", { "allow": ["warn", "error"] }]
  }
}

Never leave console.log() calls in production code. Use console.warn() and console.error() sparingly for genuine warnings and errors that help with production debugging.

FAQs

Common questions about console.log() in JavaScript:

What is the difference between console.log() and console.dir()?
console.log() displays a string representation of the value, while console.dir() displays an interactive list of the object's properties. For DOM elements, console.log() shows the HTML tree, while console.dir() shows the JavaScript object with all its properties and methods.
Can console.log() slow down my application?
In most cases, a few console.log() calls have negligible impact. However, logging inside tight loops or logging large objects repeatedly can cause noticeable slowdowns, especially if DevTools is open. Always remove or strip debug logs before deploying to production.
How do I log an object without it showing as [Object object]?
Pass the object as a separate argument instead of concatenating it with a string. Use console.log('data:', obj) instead of console.log('data: ' + obj). Alternatively, use JSON.stringify(obj, null, 2) for a formatted text representation, or console.table(obj) for a tabular view.
What does console.assert() do?
console.assert(condition, message) writes an error to the console only if the condition evaluates to false. If the condition is true, nothing happens. It is useful for sanity checks during development without adding if statements around every log.
Should I use console.log() or a debugger?
Both have their place. console.log() is quick for checking specific values and does not interrupt execution. The browser debugger (using breakpoints or the debugger statement) is better for stepping through code line by line and inspecting the full call stack. For complex issues, use the debugger. For quick checks, console.log() is faster.

Summary

console.log() is the go-to debugging tool in JavaScript, but the console object offers much more - warn(), error(), table(), group(), time(), and assert() each serve a specific purpose. Master these methods to debug more efficiently, and always remove console statements before shipping to production.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo