Using Console.Log to Its Fullest: Tips and Tricks for Enhanced Debugging and Development
2024-6-14 02:47:25 Author: hackernoon.com(查看原文) 阅读量:5 收藏

When developing, debugging, or troubleshooting web applications, console.log is one of the most frequently used tools by developers. It offers a straightforward method for outputting data to the console, which helps in understanding code execution and locating problems. Still, a lot of developers are just utilizing a small portion of console.log's capabilities.


In this article, we'll look at many console.log tips to help you with debugging and development.

Basic Tricks:

  • Multiple Values: Log multiple values with commas separating them
console.log("Message: Hi Dhanush", 10, true);

multiple values image

  • Template Literals: Use template literals for formatted strings:
const name = "Dhanush";
console.log(`Hello, ${name}!`);

template literal image

Formatting and Organization:

  • console.table: Present data in a neat table format:
const data = { name: "Dhanush", hobby: "Chess" };
console.table(data);

console table image

  • console.group/groupCollapsed: Organize logs with collapsible sections:
console.group("Network Info");
console.log("IP:", "192.168.1.1");
console.groupCollapsed("Details");  // Use for initially hidden sections
console.log("MAC Address:", "AA:BB:CC:DD:EE:FF");
console.groupEnd();
console.groupEnd();

console group image

  • console.clear: Clear the console for a fresh start.

console clear image

Advanced Debugging:

  • console.dir: Get a detailed object structure view:
const person = { name: "Dhanush", hobbies: ["youtube", "chess"] };
console.dir(person);

console dir image

  • console.assert: Log only if a condition fails (useful for debugging assumptions):
const age = 18;
console.assert(age >= 21, "User must be over 21");

console assert image

  • console.count/console.countReset: Create a counter for tracking occurrences:
console.count("API Calls");  // Increments each time called
console.count("API Calls");
console.countReset("API Calls");  // Resets the counter
console.count("API Calls");

console count image

  • console.time/console.timeEnd: Measure code execution time:
console.time("Loop Time");
for (let i = 0; i < 1000; i++) {
    // Do something
}
console.timeEnd("Loop Time");

console time image

  • console.trace: Print a stack trace to pinpoint where an error occurred.
function a() {
  function b() {
    console.trace();
  }
  b();
}

a();

console trace image

Browser Information and Interaction:

console.log(console): Explore the available console methods themselves.

console.log(console)

console image

  • console.log(navigator): Access browser information (user agent, language, etc.).
console.log(navigator)

Fun and Creative Uses:

  • ASCII Art: Create basic images using console characters:
console.log("    ____")
console.log("   / _  \\")
console.log("  ( o.o )")
console.log("   \\___/")

ASCII image

  • Simple Animations: Combine console.clear with multiple lines for basic animations.
let position = 0;
const width = 20; // Width of the console "screen"
const speed = 100; // Speed of the animation (in milliseconds)

function animate() {
    console.clear();
    let output = '';

    // Create a string with spaces followed by a dot
    for (let i = 0; i < width; i++) {
        if (i === position) {
            output += '●'; // The moving dot
        } else {
            output += ' ';
        }
    }

    console.log(output);

    // Update position
    position++;

    // Reset position to create a looping animation
    if (position >= width) {
        position = 0;
    }
}

// Set an interval to update the animation frame
setInterval(animate, speed);

Animations image

Logging Levels (Browser Dependent):

  • console.log: General information.
  • console.debug: Debugging messages (often hidden by default).
  • console.info: Informational messages.
  • console.warn: Warning messages (usually yellow text).
  • console.error: Error messages (usually red text).
console.log('This is a general information message.');

console.debug('This is a debugging message.');

console.info('This is an informational message.');

console.warn('This is a warning message.');

console.error('This is an error message.');

log image


Thanks for reading, please give a like as a sort of encouragement and also share this post in socials to show your extended support.

Follow for more ⏬

Twitter / Instagram / Github / Youtube / Newsletter / **Discord


文章来源: https://hackernoon.com/using-consolelog-to-its-fullest-tips-and-tricks-for-enhanced-debugging-and-development?source=rss
如有侵权请联系:admin#unsafe.sh