Super useful console.log tricks

Super useful console.log tricks

·

3 min read

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 utilising a small portion of console.log’s capabilities.

We’ll look at many console.log tips in this article 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);

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

Formatting and Organization:

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

  • 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.clear: Clear the console for a fresh start.

Advanced Debugging:

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

  • 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.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.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.trace: Print a stack trace to pinpoint where an error occurred.
function a() {
  function b() {
    console.trace();
  }
  b();
}

a();

Browser Information and Interaction:

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

  • 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("   \\___/")

  • 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);

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


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

Did you find this article valuable?

Support Dhanush N by becoming a sponsor. Any amount is appreciated!