DEV Community

Cover image for Moving beyond console.log
Justin
Justin

Posted on

Moving beyond console.log

Exploring the Browser Console: Practical Examples for Web Developers

For a long time my primary JavaScript debugging methods consisted of basically console.log() and console.error(). Once I learned to leverage the other browser console object's methods my JavaScript game definitely took a giant leap forwarding.

Below are 8 ways I utilize the console window object when working through JavaScript projects and scripts and practical usage of each.


1. console.log() - General Logging

Intent: Output general information for debugging or tracking program flow.

Practical Example: Use console.log to inspect variable values:

const user = { name: 'Alice', age: 30 };
console.log('User details:', user);
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.log usage


2. console.error() - Highlight Errors

Intent: Display error messages in the console with a stack trace. console.error() has different formatting helping it standout typically with a red background and error icon.

Practical Example: Log errors when API calls fail:

fetch('/api/data')
  .then(response => {
    if (!response.ok) throw new Error('Failed to fetch data');
  })
  .catch(error => console.error('Fetch error:', error));
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.error usage


3. console.warn() - Warn About Potential Issues

Intent: Highlight non-critical issues or deprecations. console.warn() has different formatting helping it standout. Typically a yellow background with a warning icon.

Practical Example: Warn about invalid user input:

const userInput = '';
if (!userInput) console.warn('User input is empty. Default value will be used.');
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.warn usage


4. console.table() - Display Data in a Table Format

Intent: Visualize arrays or objects in a tabular format for clarity. Helpful with visualizing large array of objects.

Practical Example: Inspect API response data:

const data = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];
console.table(data);
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.table usage


5. console.group() and console.groupEnd() - Organize Logs into Groups

Intent: Group related logs for better readability.

Practical Example: Debug API responses and metadata:

console.group('API Response');
console.log(`Status: ${response.status}`);
console.log(`Data:`, data);
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.group and console.groupEnd usage


6. console.time() and console.timeEnd() - Measure Performance

Intent: Track how long a block of code takes to execute. Good for performance testing and blocking time.

Practical Example: Optimize a sorting function:

console.time('Sort Timer');
const arr = [5, 3, 8, 1, 2, 50000000, 192, 50, 21, 159999, 7, 9,0];
arr.sort();
console.timeEnd('Sort Timer');
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.time and console.timeEnd usage


7. console.assert() - Test Assumptions

Intent: Log messages only when a condition is false. Helpful when you want to conditionally render an error message. Typically has a red background with a warning icon and the text "Asserting failed."

Practical Example: Validate user permissions:

const hasAccess = false;
console.assert(hasAccess, 'Access denied for the user.');
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.assert usage


8. console.trace() - Show the Call Stack

Intent: Display the call stack to trace function calls. Trace the steps leading to the console.trace() call, which is helpful when data is tracked through multiple function calls.

Practical Example: Debug where a function was invoked:

function fetchData() {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => showData(json))
}  
function showData(fData) {
  console.trace('Show data', fData);
}

const fData = fetchData();
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.trace usage


9. console.count() - Count Log Occurrences

Intent: Count how many times a line of code has been executed. Helpful in instances where you need to count the number of times a function has been called or a loop has looped.

Practical Example: Count loops:

const array1 = ['a', 'b', 'c', 'd'];
for (const element of array1) {
  console.count()
}
Enter fullscreen mode Exit fullscreen mode

Example Output:

Screenshot of console.count usage


10. console.clear() - Clean Up the Console

Intent: Clear cluttered logs during testing.

Practical Usage:

console.clear();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)