Explain Codes LogoExplain Codes Logo

How do I print debug messages in the Google Chrome JavaScript Console?

javascript
console-logging
debugging
javascript-console
Alex KataevbyAlex Kataev·Oct 14, 2024
TLDR

Harness the power of console.log() to print messages in Chrome's JavaScript Console for debugging purposes:

console.log("Debug: message goes here");

Differentiate your log message types by using console.error() for errors, console.warn() for warnings, and console.info() for informational messages. Condition-based logging can be achieved with console.assert(condition, "Message"). To logically group messages, you can use console.group() and console.groupEnd(). Use console.time("Label") and console.timeEnd("Label") to time your operations and discover potential bottlenecks.

Here's a micro-sample of how to combine assertions with time measurement:

console.assert(someVariable === expectedValue, "Oops: the variable didn't meet the expected value"); console.time("Duration of someFunction"); someFunction(); console.timeEnd("Duration of someFunction"); // A stopwatch, but nerdier

Advanced console usage

Detailed object viewing and stack traces

For detailed examination of complex objects, use %o:

console.log('Here is the object, inspector: %o', complexObject); // Not "objectively" complex, just a term

To trace back the execution of a function, console.trace() is your friend:

console.trace('Detective, here is the crime scene.'); // Not an actual crime, we promise

Reclaiming the original console behavior

Sometimes, web applications or libraries override the default console methods. You need to refresh the page to reclaim the original behavior, or for a script-based solution, keep a backup reference to the original methods:

const originalLog = console.log.bind(console); // "I want my log back, log back, log back..."

Ensuring console existence

Certain environments or browsers may not have the console object. Ensure it's availability or create fallbacks to avoid errors:

if (!window.console) { window.console = { log: function() {} /* , add more methods as per your use */ }; }

Formatted logging

When you want formatted output, like printf in C, use string substitutions:

console.log("Hello, %s. You have %i problems.", userName, problemCount); // I mean, who doesn't?

Scenarios: Debugging in Console

Performance checkpoints

Use console.time() and console.timeEnd() as virtual checkpoints for tracking performance:

console.time("Fetching Data"); fetchData().then(() => { console.timeEnd("Fetching Data"); // Ding! Your data is ready });

Interactive object analysis

Delve into object structures during runtime by logging them with %o:

console.log("Behold the object: %o", anObject);

Call stack tracing

If you'd like a stack trace without causing a scene (🧱💥), console.trace() is your go-to:

console.trace("Stack trace sneak peak");

Debugging across various browsers

Ensure console function availability to maintain consistency across browsers:

function safeLog() { if (console !== undefined && console.log) { console.log.apply(console, arguments); } }