Home > Web Front-end > JS Tutorial > Moving beyond console.log

Moving beyond console.log

Susan Sarandon
Release: 2024-12-18 08:31:09
Original
301 people have browsed it

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);
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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));
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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.');
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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);
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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();
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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:

const user = { name: 'Alice', age: 30 };
console.log('User details:', user);
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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:

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

Example Output:

Moving beyond console.log


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:

const userInput = '';
if (!userInput) console.warn('User input is empty. Default value will be used.');
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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 data = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];
console.table(data);
Copy after login
Copy after login

Example Output:

Moving beyond console.log


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

Intent: Clear cluttered logs during testing.

Practical Usage:

console.group('API Response');
console.log(`Status: ${response.status}`);
console.log(`Data:`, data);
console.groupEnd();
Copy after login
Copy after login

The above is the detailed content of Moving beyond console.log. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template